package com.ctshk.rpc.order.tour.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.service.support.BaseService;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.finance.json.FileJson;
import com.ctshk.rpc.finance.req.bill.BillAddCollectionReq;
import com.ctshk.rpc.finance.req.bill.BillOperateRefundReq;
import com.ctshk.rpc.finance.req.onaccount.UseQuotaReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.finance.service.IFinanceOnAccountCurrencyQuotaService;
import com.ctshk.rpc.insurance.dto.*;
import com.ctshk.rpc.insurance.req.InsuranceProductReq;
import com.ctshk.rpc.insurance.req.InsuranceUnderwritingReq;
import com.ctshk.rpc.insurance.req.tp.*;
import com.ctshk.rpc.insurance.service.IInsuranceService;
import com.ctshk.rpc.iotc.dto.OperateBankPreferenceQueryDTO;
import com.ctshk.rpc.iotc.dto.OperatePromotionQueryDTO;
import com.ctshk.rpc.iotc.req.*;
import com.ctshk.rpc.iotc.service.IOperateBankPreferenceService;
import com.ctshk.rpc.iotc.service.IOperatePromotionService;
import com.ctshk.rpc.order.tour.code.CollectionTypeIdCode;
import com.ctshk.rpc.order.tour.code.IsDeletedCode;
import com.ctshk.rpc.order.tour.code.*;
import com.ctshk.rpc.order.tour.constant.Constants;
import com.ctshk.rpc.order.tour.dto.*;
import com.ctshk.rpc.order.tour.dto.custom.*;
import com.ctshk.rpc.order.tour.entity.*;
import com.ctshk.rpc.order.tour.mapper.*;
import com.ctshk.rpc.order.tour.req.*;
import com.ctshk.rpc.order.tour.req.custom.*;
import com.ctshk.rpc.order.tour.service.ISeriesOrderCollectionService;
import com.ctshk.rpc.order.tour.service.ISeriesOrderInsuranceService;
import com.ctshk.rpc.order.tour.service.ISeriesOrderService;
import com.ctshk.rpc.order.tour.util.PacificUtil;
import com.ctshk.rpc.order.tour.util.Utils;
import com.ctshk.rpc.order.tour.vo.RelationInfoJsonBankPreference;
import com.ctshk.rpc.order.tour.vo.RelationInfoJsonDiscount;
import com.ctshk.rpc.order.tour.vo.SalesReceiptJson;
import com.ctshk.rpc.stamp.dto.LevyDTO;
import com.ctshk.rpc.stamp.req.LevyRequest;
import com.ctshk.rpc.stamp.service.ILevyService;
import com.ctshk.rpc.system.dto.*;
import com.ctshk.rpc.system.dto.member.ContactQueryDTO;
import com.ctshk.rpc.system.dto.member.CrmAccountDTO;
import com.ctshk.rpc.system.req.MainDataCurrencyUpdateStatusReq;
import com.ctshk.rpc.system.req.MainDataPaymentRefundTypeIdReq;
import com.ctshk.rpc.system.req.crm.member.CrmMemberQueryReq;
import com.ctshk.rpc.system.req.crm.member.CrmMemberUpdatePointsReq;
import com.ctshk.rpc.system.service.*;
import com.ctshk.rpc.tour.dto.TripBasicInformationDTO;
import com.ctshk.rpc.tour.dto.schedule.SeriesTripScheduleDTO;
import com.ctshk.rpc.tour.dto.schedule.SeriesTripScheduleDataDTO;
import com.ctshk.rpc.tour.req.SeriesTripReq;
import com.ctshk.rpc.tour.req.trip.TripInsuranceReq;
import com.ctshk.rpc.tour.service.ISeriesTripScheduleService;
import com.ctshk.rpc.tour.service.ISeriesTripService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;



/**
 * <p>
 * 系列团游客收款 服务实现类
 * </p>
 *
 * @author 谭响
 * @since 2021-01-18
 */
@Slf4j
@DubboService
public class SeriesOrderCollectionServiceImpl extends ServiceImpl<SeriesOrderCollectionMapper, SeriesOrderCollection> implements ISeriesOrderCollectionService, BaseService {
    @Autowired
    private SeriesOrderCollectionMapper seriesOrderCollectionMapper;
    @Autowired
    private SeriesOrderTouristInfoMapper seriesOrderTouristInfoMapper;
    @Autowired
    private SeriesOrderAmountStatisticsMapper seriesOrderAmountStatisticsMapper;
    @DubboReference
    private IMainDataCurrencyService iMainDataCurrencyService;
    @DubboReference
    private IOperateBankPreferenceService iOperateBankPreferenceService;
    @Autowired
    private SeriesOrderMapper seriesOrderMapper;
    @DubboReference
    private ISeriesTripScheduleService iSeriesTripScheduleService;
    @Autowired
    private SeriesOrderReceiptDetailsMapper seriesOrderReceiptDetailsMapper;
    @Autowired
    private SeriesOrderTouristOtherFeeMapper seriesOrderTouristOtherFeeMapper;
    @Autowired
    private SeriesOrderTouristFeeAdjustMapper seriesOrderTouristFeeAdjustMapper;
    @DubboReference
    private IOperatePromotionService iOperatePromotionService;
    @DubboReference
    private ICrmMemberService iCrmMemberService;
    @DubboReference
    private IInsuranceService iInsuranceService;
    @DubboReference
    private ISeriesTripService iSeriesTripService;
    @DubboReference
    private ISysUserService iSysUserService;
    @Autowired
    private SeriesOrderReceiptMapper seriesOrderReceiptMapper;
    @Autowired
    private SeriesOrderReceiptTouristMapper seriesOrderReceiptTouristMapper;
    @DubboReference
    private IMainDataFieldDataService iMainDataFieldDataService;
    @DubboReference
    private ILevyService iLevyService;
    @DubboReference
    private IMainDataPaymentRefundTypeService iMainDataPaymentRefundTypeService;
    @Autowired
    private ISeriesOrderService iSeriesOrderService;
    @DubboReference
    private ISysDepartmentService iSysDepartmentService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @DubboReference
    private IFinanceBillService iFinanceBillService;
    @Autowired
    private SeriesOrderTouristInfoMapper orderTouristInfoMapper;
    @Autowired
    private SeriesOrderInsuranceMapper orderInsuranceMapper;
    @Autowired
    private SeriesOrderInsurancePriceTouristMapper orderInsurancePriceTouristMapper;
    @Autowired
    private SeriesOrderReceiptInsuranceMapper orderReceiptInsuranceMapper;
    @Autowired
    private SeriesOrderInsuranceJoinMapper orderInsuranceJoinMapper;

    @Autowired
    ISeriesOrderInsuranceService orderReceiptInsuranceService;

    @DubboReference
    private IFinanceOnAccountCurrencyQuotaService financeOnAccountCurrencyQuotaService;
    @Autowired
    private SeriesOrderTouristVisaMapper orderTouristVisaMapper;

    @Value("${schedule.config.domain}")
    private String domain;

    @Value("${schedule.config.app-name}")
    private String appName;

    @Value("${schedule.config.password}")
    private String password;

    /**
     * 银联优惠计算
     */
    @Override
    public Result<SeriesOrderCollectionCalculationDTO> calculation(SeriesOrderCollectionCalculationReq req, TokenUser currentUser) {
        SeriesOrderCollectionCalculationDTO dto = new SeriesOrderCollectionCalculationDTO();
        //本次支付总金额
        BigDecimal totalPaidInAmount = BigDecimal.ZERO;
        for (SeriesOrderCollectionCalculationItemReq item : req.getItems()) {
            BigDecimal hkdAmount = iMainDataCurrencyService.getHkdAmount(item.getCurrencyTypeId(), item.getCurrencyPaidInAmount());
            if (hkdAmount == null){
                hkdAmount = BigDecimal.ZERO;
            }
            totalPaidInAmount = totalPaidInAmount.add(hkdAmount);
        }
        //银联优惠总金额
        BigDecimal totalBankCountAmount = BigDecimal.ZERO;
        //人均银联优惠金额
        BigDecimal averageBankCountAmount = BigDecimal.ZERO;
        //银行优惠(大客户挂账)
        SeriesOrderCollectionCalculationItemReq firstItem = req.getItems().get(0);
        OperateBankConformQueryReq bankPreferenceQueryReq = new OperateBankConformQueryReq();
        bankPreferenceQueryReq.setId(req.getBankPreferenceId());
        bankPreferenceQueryReq.setBusinessType(2);
        bankPreferenceQueryReq.setCardNumber(firstItem.getPayer());
        bankPreferenceQueryReq.setChannelId(12345678902L);
        bankPreferenceQueryReq.setRelationId(req.getScheduleId());
        bankPreferenceQueryReq.setUserId(currentUser.getId());
        bankPreferenceQueryReq.setTotalPaidIn(totalPaidInAmount);
        bankPreferenceQueryReq.setDiscountObjectId(12345678L);
        Result<OperateBankPreferenceQueryDTO> result = iOperateBankPreferenceService.queryConform(bankPreferenceQueryReq);
        if (!result.isSuccess()) {
            throw new BusinessException(SystemError.SYS_439,"運營中心","錯誤信息："+result.getMsg());
        }
        OperateBankPreferenceQueryDTO queryDTO = result.getData();
        if (Objects.equals(queryDTO.getDiscountType(), NumberConstant.ONE.getValue())) {
            //优惠类型：满减
            if (totalPaidInAmount.compareTo(queryDTO.getFullAmount()) >= 0) {
                BigDecimal bankPreference = totalPaidInAmount.subtract(queryDTO.getReductionAmount());
                totalBankCountAmount = totalBankCountAmount.add(bankPreference);
            }
        } else if (Objects.equals(queryDTO.getDiscountType(), NumberConstant.TWO.getValue())) {
            //优惠类型：折扣
            BigDecimal bankPreference = totalPaidInAmount.subtract(totalPaidInAmount.multiply(
                    BigDecimal.valueOf(queryDTO.getDiscountPercent())));
            if (bankPreference.compareTo(queryDTO.getMaxDiscount()) > 0) {
                totalBankCountAmount = totalBankCountAmount.add(queryDTO.getMaxDiscount());
            } else {
                totalBankCountAmount = totalBankCountAmount.add(bankPreference);
            }
        }
        //人均优惠金额
        averageBankCountAmount = totalBankCountAmount.divide(new BigDecimal(req.getItems().size()), 2, BigDecimal.ROUND_HALF_DOWN);

        dto.setTotalPaidInAmount(totalPaidInAmount);
        dto.setTotalBankPreferenceAmount(totalBankCountAmount);
        List<SeriesOrderCollectionCalculationItemDTO> itemList = new ArrayList<>();
        for (SeriesOrderCollectionCalculationItemReq item : req.getItems()) {
            SeriesOrderCollectionCalculationItemDTO itemDTO = EntityUtil.copy(item,SeriesOrderCollectionCalculationItemDTO.class);
            itemDTO.setCurrencyPaidInAmount(item.getCurrencyPaidInAmount().subtract(averageBankCountAmount));
            itemList.add(itemDTO);
        }
        for (SeriesOrderCollectionCalculationItemReq item : req.getItems()) {
            SeriesOrderCollectionCalculationItemDTO itemDTO = EntityUtil.copy(item,SeriesOrderCollectionCalculationItemDTO.class);
            itemDTO.setCurrencyPaidInAmount(averageBankCountAmount);
            itemList.add(itemDTO);
        }
        dto.setItemList(itemList);
        return Result.success(dto);
    }



    /**
     * 收款
     *
     * @param req
     * @param currentUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(CustomOrderCollectionAddReq req, TokenUser currentUser) {
        Long scheduleId = req.getScheduleId();
        //收款方式标识(1：挂账，2：内部挂账，3：其他)
        int collectWay = 3;
        if (Objects.equals(CollectionWayIdCode.ON_ACCOUNT.getCode(),req.getCollectionWayId())){
            //挂账
            collectWay = 1;
        }else if (Objects.equals(CollectionWayIdCode.INTERNAL_ACCOUNT.getCode(),req.getCollectionWayId())){
            //内部挂账
            collectWay = 2;
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(req.getTripNumber())){
                throw new BusinessException(SystemError.SYS_409,"團號");
            }
            //根据团号获取团期ID
            Long id = iSeriesTripScheduleService.queryIdByTripNumber(req.getTripNumber());
            if (id == null){
                throw new BusinessException(SystemError.CUSTOM_3006);
            }
            scheduleId = id;
        }
        SeriesOrder order = seriesOrderMapper.selectById(req.getOrderId());
        if (order == null || Objects.equals(order.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        //判断是否可以收款
        QueryWrapper<SeriesOrderAmountStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SeriesOrderAmountStatistics::getOrderId, req.getOrderId());
        SeriesOrderAmountStatistics statistics = seriesOrderAmountStatisticsMapper.selectOne(queryWrapper);
        if (statistics == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        //本次收款总金额
        BigDecimal totalReciveAmount = BigDecimal.ZERO;
        for (CustomOrderCollectionAddItemReq item : req.getItems()){
            BigDecimal hkdAmount = iMainDataCurrencyService.getHkdAmount(item.getCurrencyTypeId(), item.getPaidInAmount());
            totalReciveAmount = totalReciveAmount.add(hkdAmount);
        }

        /*if (totalReciveAmount.compareTo(statistics.getRemainingReceivables()) > 0){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4009);
        }*/
        //更新订单统计
        statistics.setTotalPaidIn(statistics.getTotalPaidIn().add(totalReciveAmount));
        statistics.setRemainingReceivables(statistics.getRemainingReceivables().subtract(totalReciveAmount));
        int updateStatistics = seriesOrderAmountStatisticsMapper.updateById(statistics);
        if (updateStatistics <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //获取最小定金
        SeriesTripScheduleDTO tripSchedule = iSeriesTripScheduleService.getTripScheduleId(scheduleId);
        if (tripSchedule == null){
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        //是否计算印花税
        boolean isTax = false;
        if(Objects.equals(Constants.AREA_HK, tripSchedule.getSeriesTripScheduleDataDTO().getDeparturePlaceId())
                && !Objects.equals(Constants.AREA_HK, tripSchedule.getSeriesTripScheduleDataDTO().getDestinationId())) {
            isTax = true;
        }
        //数据抬头
        Long firstTouristId = req.getItems().get(0).getTouristId();
        SeriesOrderTouristInfo firstTourist = seriesOrderTouristInfoMapper.selectById(firstTouristId);
        String receiptHeader = tripSchedule.getSeriesTripScheduleTeamRuleDTO().getChargePersonName();
        if (StringUtils.isNotBlank(firstTourist.getCnFullname())){
            receiptHeader = firstTourist.getCnFullname();
        }else{
            receiptHeader = firstTourist.getEnFullname();
        }

        //收据（立即打印收据用到）
        SeriesOrderReceipt receipt = null;
        //收据关联旅客（立即打印收据用到）
//        List<CustomizedOrderReceiptTourist> receiptTouristList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        //是否立即打印收据
        if (req.getIsPrint().intValue() == NumberConstant.ONE.getValue()){
            receipt = new SeriesOrderReceipt();
            receipt.setId(SnowflakeIdWorker.nextId());
            receipt.setOrderId(req.getOrderId());
            receipt.setScheduleId(order.getScheduleId());
            receipt.setReceiptHeader(receiptHeader);
            receipt.setReceiptNumber(getReceiptNumber(currentUser.getId()));
            receipt.setReceiptType(1);
            receipt.setCreateTime(now);
            receipt.setGmtCreate(now);
            receipt.setCreateId(currentUser.getId());
            receipt.setReceiptStatus(1);
            receipt.setIsDeleted(0);
        }
        //新增收款列表
        List<SeriesOrderCollection> collectionList = new ArrayList<>();
        //    List<Long> collectionIdList = new ArrayList<>();
        //总收款金额
        BigDecimal totalPaidInAmount = new BigDecimal(0);
        //印花税金额
        BigDecimal stampDutyAmount = BigDecimal.ZERO;
        //收款记录ID
        List<Long> collectionId = new ArrayList<>();
        //旅客信息
        List<ReceiptTouristInfoDTO> touristInfoDTOList = new ArrayList<>();
        //新增财务认款请求参数
        List<BillAddCollectionReq> addListReq = new ArrayList<>();

        //旅客收据详情列表
        List<TouristReceiptInfoDTO> touristReceiptInfoList = new ArrayList<>();

        //使用挂账记录列表
        List<UseQuotaReq> useQuotaReqList = new ArrayList<>();
        //支付方式
        List<String> payMethodList = new ArrayList<>();
        //付款方
        List<String> payerList = new ArrayList<>();

        for (CustomOrderCollectionAddItemReq item : req.getItems()) {
            payMethodList.add(item.getCollectionWay());
            payerList.add(item.getPayer());
            //游客统计
            QueryWrapper<SeriesOrderTouristInfo> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getOrderId, req.getOrderId());
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getId, item.getTouristId());
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getIsDeleted, 0);
            SeriesOrderTouristInfo touristInfo = orderTouristInfoMapper.selectOne(queryWrapper2);

            //旅客收据详情
            TouristReceiptInfoDTO touristReceiptInfoDTO = new TouristReceiptInfoDTO();
            touristReceiptInfoDTO.setTouristId(touristInfo.getId());
            touristReceiptInfoDTO.setReceiptAmount(item.getPaidInAmount());
            touristReceiptInfoList.add(touristReceiptInfoDTO);

            //收据旅客信息
            ReceiptTouristInfoDTO touristInfoDTO = EntityUtil.copy(touristInfo,ReceiptTouristInfoDTO.class);
            touristInfoDTOList.add(touristInfoDTO);
            if (touristInfo.getPayStatus().intValue() == NumberConstant.ONE.getValue()){
                //第一次收款，收款金额不能比“預設訂金+代收費用”的金額低
                BigDecimal minDeposit = null;
                try{
                    minDeposit = tripSchedule.getSeriesTripScheduleTeamRuleDTO().getMinDeposit();
                }catch (Exception e){
                    minDeposit = BigDecimal.ZERO;
                }
                BigDecimal miniAmount = touristInfo.getCollectionFee().add(minDeposit);
                BigDecimal hkdAmount = iMainDataCurrencyService.getHkdAmount(item.getCurrencyTypeId(), item.getPaidInAmount());
                if (miniAmount.compareTo(hkdAmount) > 0){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4042,touristInfo.getCnFullname(),miniAmount);
                }
            }
            if (req.getBankPreferenceId() != null){
                //使用银行优惠
                if (touristInfo.getTotalPaidIn().compareTo(BigDecimal.ZERO) > 0 && touristInfo.getPayStatus().intValue() != NumberConstant.ONE.getValue()){
                    //实收金额大于0不能使用银行优惠
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4043,touristInfo.getCnFullname());
                }
            }
            //计算印花税
            if (isTax){
                //是否计算过代收费用（代收费用印花税只计算一次）
                if (touristInfo.getIsReceiptCalculated() != null && touristInfo.getIsReceiptCalculated().intValue() == NumberConstant.ONE.getValue()){
                    //是
                    stampDutyAmount = stampDutyAmount.add(item.getPaidInAmount().multiply(new BigDecimal(Constants.STAMP_DUTY_RATIO)));
                }else{
                    //否
                    stampDutyAmount = stampDutyAmount.add((item.getPaidInAmount().subtract(touristInfo.getCollectionFee())).multiply(new BigDecimal(Constants.STAMP_DUTY_RATIO)));
                    touristInfo.setIsReceiptCalculated(1);
                }
            }
            //收款记录
            SeriesOrderCollection collection = EntityUtil.copy(item, SeriesOrderCollection.class);
            collection.setId(SnowflakeIdWorker.nextId());
            collection.setPayerId(req.getPayerId());
            BigDecimal hkdAmount = iMainDataCurrencyService.getHkdAmount(item.getCurrencyTypeId(), item.getPaidInAmount());
            collection.setCurrencyPaidInAmount(item.getPaidInAmount());
            collection.setPaidInAmount(hkdAmount);
            collection.setExchangeRate(new BigDecimal(item.getExchangeRate()));
            collection.setGmtCreate(now);
            collection.setIsDeleted(0);
            collection.setCreateId(currentUser.getId());
            collection.setIsPos(req.getIsPos());
            String collectionNumber = StrConstant.SKD.getValue() + DateUtil.fmt(LocalDateTime.now(),"yyMMddHHmmss" + CharUtil.getRandomStr(2));
            collection.setCollectionNumber(collectionNumber);
            collection.setStatus(3);
            collection.setOrderId(req.getOrderId());
            collection.setScheduleId(req.getScheduleId());
            collection.setIsPrint(req.getIsPrint());
            //记录收据Json属性
            collectionId.add(collection.getId());

            //财务认款请求参数
            BillAddCollectionReq addReq = packBillAddCollectionReq(item,collection,tripSchedule,order,currentUser.getId());
            addListReq.add(addReq);

            //内部挂账
            if (collectWay == 1 && Objects.equals(order.getCustomerType(),2)){
                UseQuotaReq useQuotaReq = packOnAccountUsageAddReq(touristInfo,order,collection,order.getBigClientId(),order.getBigClientName(),collectWay,currentUser.getId());
                useQuotaReqList.add(useQuotaReq);
            }else if (collectWay == 2){
                UserDTO userDTO = iSysUserService.queryCacheUser(currentUser.getId());
                UseQuotaReq useQuotaReq = packOnAccountUsageAddReq(touristInfo,order,collection,userDTO.getDeptId(),userDTO.getDept(),collectWay,currentUser.getId());
                useQuotaReqList.add(useQuotaReq);
            }

            //更新旅客金额统计
            touristInfo.setTotalPaidIn(touristInfo.getTotalPaidIn().add(collection.getPaidInAmount()));
            touristInfo.setRemainingReceivables(touristInfo.getRemainingReceivables().subtract(collection.getPaidInAmount()));
            //是否全部收完
            if(touristInfo.getTotalPaidIn().compareTo(touristInfo.getTotalReceivables()) >= 0){
                touristInfo.setPayStatus(3);
            } else if(touristInfo.getTotalPaidIn().compareTo(new BigDecimal(0)) > 0 &&
                    touristInfo.getTotalPaidIn().compareTo(touristInfo.getTotalReceivables()) < 0){
                touristInfo.setPayStatus(2);
            }
            collection.setTotalReceivables(touristInfo.getTotalReceivables());
            collectionList.add(collection);
            //    collectionIdList.add(collection.getId());
            //更新旅客信息
            int update = orderTouristInfoMapper.updateById(touristInfo);
            if (update <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
            //总收款金额
            totalPaidInAmount = totalPaidInAmount.add(collection.getPaidInAmount());
        }
        if (receipt != null){
            receipt.setReceiptAmount(totalPaidInAmount);
            receipt.setIncludeTouristNum(collectionList.size());
        }
        //银行优惠(大客户挂账)
        Result<OperateBankPreferenceQueryDTO> preferenceQueryDTOResult = null;
        CustomOrderCollectionAddItemReq firstItem = req.getItems().get(0);
        if (req.getBankPreferenceId() != null) {
            OperateBankConformQueryReq bankPreferenceQueryReq = new OperateBankConformQueryReq();
            bankPreferenceQueryReq.setId(req.getBankPreferenceId());
            bankPreferenceQueryReq.setBusinessType(1);
            bankPreferenceQueryReq.setCardNumber(firstItem.getPayer());
            bankPreferenceQueryReq.setChannelId(12345678902L);
            bankPreferenceQueryReq.setRelationId(req.getScheduleId());
            bankPreferenceQueryReq.setUserId(currentUser.getId());
            bankPreferenceQueryReq.setTotalPaidIn(totalPaidInAmount);
            bankPreferenceQueryReq.setDiscountObjectId(12345678L);
            preferenceQueryDTOResult = iOperateBankPreferenceService.queryConform(bankPreferenceQueryReq);
        }
        //总银行优惠金额
        BigDecimal totalBankPreferenceAmount = new BigDecimal(0);
        //银行优惠
        List<SeriesOrderCollection> bankPreferenceList = new ArrayList<>();
        if (preferenceQueryDTOResult != null && preferenceQueryDTOResult.isSuccess() && preferenceQueryDTOResult.getData() != null) {
            OperateBankPreferenceQueryDTO preferenceQueryDTO = preferenceQueryDTOResult.getData();
            if (Objects.equals(preferenceQueryDTO.getDiscountType(), NumberConstant.ONE.getValue())) {
                //优惠类型：满减
                if (totalPaidInAmount.compareTo(preferenceQueryDTO.getFullAmount()) >= 0) {
                    BigDecimal bankPreference = totalPaidInAmount.subtract(preferenceQueryDTO.getReductionAmount());
                    totalBankPreferenceAmount = totalBankPreferenceAmount.add(bankPreference);
                }
            } else if (Objects.equals(preferenceQueryDTO.getDiscountType(), NumberConstant.TWO.getValue())) {
                //优惠类型：折扣
                BigDecimal bankPreference = totalPaidInAmount.subtract(totalPaidInAmount.multiply(
                        BigDecimal.valueOf(preferenceQueryDTO.getDiscountPercent())));
                if (bankPreference.compareTo(preferenceQueryDTO.getMaxDiscount()) > 0) {
                    totalBankPreferenceAmount = totalBankPreferenceAmount.add(preferenceQueryDTO.getMaxDiscount());
                } else {
                    totalBankPreferenceAmount = totalBankPreferenceAmount.add(bankPreference);
                }
            }
            //人均优惠金额
            BigDecimal avgDiscountAmount = totalBankPreferenceAmount.divide(new BigDecimal(collectionList.size()), 2, BigDecimal.ROUND_HALF_DOWN);
            //全款
            MainDataFieldDataDTO collectionTypeDTO = iMainDataFieldDataService.queryFieldData(CollectionTypeIdCode.FULL.getCode());
            if(collectionTypeDTO == null) {
                return Result.failed(SystemError.SYS_411);
            }
            //遍历收款
            for (int i = 0;i < collectionList.size();i++){
                SeriesOrderCollection collection = collectionList.get(i);
                collection.setCollectionTypeId(collectionTypeDTO.getId());
                collection.setCollectionType(collectionTypeDTO.getFieldValue());
                collection.setCollectionWayId(CollectionWayIdCode.BANK_DISCOUNT.getCode());
                collection.setCollectionWay(CollectionWayIdCode.BANK_DISCOUNT.getMsg());
                //新增银行优惠收款记录
                SeriesOrderCollection bankPreferenceCollection = EntityUtil.copy(collection, SeriesOrderCollection.class);
                bankPreferenceCollection.setId(SnowflakeIdWorker.nextId());
                bankPreferenceCollection.setCurrencyType(CurrencyIdCode.HKD.getMsg());
                bankPreferenceCollection.setCurrencyTypeId(CurrencyIdCode.HKD.getCode());
                bankPreferenceCollection.setCollectionTypeId(collectionTypeDTO.getId());
                bankPreferenceCollection.setCollectionType(collectionTypeDTO.getFieldValue());
                bankPreferenceCollection.setCollectionWayId(CollectionWayIdCode.BANK_DISCOUNT.getCode());
                bankPreferenceCollection.setCollectionWay(CollectionWayIdCode.BANK_DISCOUNT.getMsg());
                if (i < (collectionList.size() - 1)){
                    //非最后一个正常取值
                    collection.setCurrencyPaidInAmount(avgDiscountAmount);
                    bankPreferenceCollection.setCurrencyPaidInAmount(avgDiscountAmount);
                }else{
                    //最后一个旅客的优惠取余数
                    BigDecimal remainDiscountAmount = totalBankPreferenceAmount.subtract(avgDiscountAmount.multiply(new BigDecimal(collectionList.size() - 1)));
                    collection.setCurrencyPaidInAmount(remainDiscountAmount);
                    bankPreferenceCollection.setCurrencyPaidInAmount(remainDiscountAmount);
                }
                //清空copy的部分不需要内容
                bankPreferenceCollection.setPayer(null);
                bankPreferenceCollection.setRemark(null);
                bankPreferenceCollection.setCollectionVoucherNum(null);
                bankPreferenceCollection.setCollectionVoucherJson(null);
                //金额为0不作处理
                if(bankPreferenceCollection.getCurrencyPaidInAmount().compareTo(new BigDecimal(0)) == 0) {
                    continue;
                }
                //收款记录关联json
                RelationInfoJsonBankPreference relationInfoJson = new RelationInfoJsonBankPreference();
                relationInfoJson.setDiscountId(req.getBankPreferenceId());
                bankPreferenceCollection.setRelationInfoJson(JSON.toJSONString(relationInfoJson));
                bankPreferenceList.add(bankPreferenceCollection);
            }
            //合并数组
            collectionList.addAll(bankPreferenceList);

            //使用优惠
            OperateBankDeductReq deductReq = new OperateBankDeductReq();
            deductReq.setId(req.getBankPreferenceId());
            deductReq.setTotalPaidIn(totalBankPreferenceAmount);
            deductReq.setRelationId(req.getScheduleId());
            deductReq.setProductNumber(order.getScheduleNumber());
            deductReq.setProductName(order.getTripTitle());
            deductReq.setCardNumber(firstItem.getPayer());
            deductReq.setBusinessType(SystemBusinessType.OUTBOUND_TRAVEL.getCode());
            //TODO
            /*deductReq.setDiscountObjectId();
            deductReq.setChannelId();*/
            Result deduct = iOperateBankPreferenceService.deduct(deductReq, currentUser);
            if (deduct == null || deduct.getCode() != 0){
                log.error("使用银联优惠报错：code = "+deduct.getCode()+" ,msg = " + deduct.getMsg());
                throw new BusinessException(SystemError.SYS_408);
            }

        }
        //批量新增收款记录
        boolean bl = saveBatch(collectionList);
        if (!bl){
            throw new BusinessException(SystemError.SYS_437);
        }
        //是否立即打印收据
        if (req.getIsPrint().intValue() == NumberConstant.ONE.getValue()){
            //新增收据
            int insertReceipt = seriesOrderReceiptMapper.insert(receipt);
            if (insertReceipt <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
            //收据关联旅客
            /*if (receiptTouristList.size() > 0){
                //批量新增收据关联旅客
                Integer batch = orderReceiptTouristMapper.insertBatchSomeColumn(receiptTouristList);
                if (batch < receiptTouristList.size()){
                    throw new BusinessException(SystemError.SYS_437);
                }
            }*/
            //销售收据
            SeriesOrderReceiptDetails receiptDetails = new SeriesOrderReceiptDetails();
            receiptDetails.setId(SnowflakeIdWorker.nextId());
            receiptDetails.setOrderId(order.getId());
            receiptDetails.setScheduleId(order.getScheduleId());
            receiptDetails.setReceiptId(receipt.getId());
            receiptDetails.setReceiptType(1);
            receiptDetails.setTouristName(receiptHeader);
            receiptDetails.setCustomerRights(tripSchedule.getSeriesTripScheduleDataDTO().getCustomerRights());
            receiptDetails.setReceiptStatus(1);
            receiptDetails.setTeaPartyDate(tripSchedule.getSeriesTripScheduleTeamRuleDTO().getTeaPartyDate());
            receiptDetails.setTeaPartyTime(tripSchedule.getSeriesTripScheduleTeamRuleDTO().getTeaPartyTime());
            if (isTax){
                receiptDetails.setStampDutyAmount(stampDutyAmount);
            }

            //销售收据json
            SalesReceiptJson salesReceiptJson = new SalesReceiptJson();
            salesReceiptJson.setPayMethod(payMethodList);
            salesReceiptJson.setPayer(payerList);
            salesReceiptJson.setTouristReceiptInfoList(touristReceiptInfoList);
            salesReceiptJson.setCollectionIdList(collectionId);
            salesReceiptJson.setTouristInfoDTOList(touristInfoDTOList);
            salesReceiptJson.setTourCode(tripSchedule.getTripNumber());
            salesReceiptJson.setDays(tripSchedule.getSeriesTripScheduleDataDTO().getTravelDays());
            salesReceiptJson.setDepartureDate(tripSchedule.getDepartureDate());
            salesReceiptJson.setDeliveryDate(tripSchedule.getDepartureDate().plusDays(tripSchedule.getSeriesTripScheduleDataDTO().getTravelDays()));
            salesReceiptJson.setDepDate(CharUtil.getWeekDay(tripSchedule.getDepartureDate().getDayOfWeek().getValue()));
            salesReceiptJson.setRoute(tripSchedule.getSeriesTripScheduleDataDTO().getTitle());
            salesReceiptJson.setEnquiryNo(Utils.getRandom6());
            salesReceiptJson.setEnquiryTimeTel(Constants.QUERY_TIME);
            /*salesReceiptJson.setItemList(itemDTOList);
            salesReceiptJson.setWayList(wayDTOList);
            salesReceiptJson.setRemarkList(remarkDTOList);
            salesReceiptJson.setCollectionIdList(collectionIdList);*/
            salesReceiptJson.setReceiptNumber(Utils.getReceiptNumberB());
            salesReceiptJson.setCollectionFee(statistics.getCollectionFee());
            salesReceiptJson.setAdjustmentCost(statistics.getAdjustmentCost());
            salesReceiptJson.setOtherAmount(statistics.getOtherAmount());
            salesReceiptJson.setGroupFee(statistics.getTotalTourFee());
            salesReceiptJson.setTotalReceivables(statistics.getTotalReceivables());
            salesReceiptJson.setPaidAmount(statistics.getTotalPaidIn());
            salesReceiptJson.setPayAmount(totalReciveAmount.subtract(totalBankPreferenceAmount));
            salesReceiptJson.setRemainingAmount(statistics.getRemainingReceivables());
            //定制包团须知
            salesReceiptJson.setTourFeeInclude(tripSchedule.getSeriesTripScheduleDataDTO().getTourFeeInclude());
            salesReceiptJson.setTourFeeExclude(tripSchedule.getSeriesTripScheduleDataDTO().getTourFeeExclude());
            salesReceiptJson.setSignNotice(tripSchedule.getSeriesTripScheduleDataDTO().getSignNotice());
            salesReceiptJson.setRemark(tripSchedule.getSeriesTripScheduleDataDTO().getRemark());
            receiptDetails.setReceipJson(JSON.toJSONString(salesReceiptJson));
            //新增销售收据
            int insertDetial = seriesOrderReceiptDetailsMapper.insert(receiptDetails);
            if (insertDetial <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
            //对接财务认款
            Result result = iFinanceBillService.addCollection(addListReq);
            if (result == null || !result.isSuccess()){
                throw new BusinessException(SystemError.SYS_437);
            }
            //新增财务挂账使用记录
            if (useQuotaReqList.size() > 0 && collectWay != 3){
                Result result1 = financeOnAccountCurrencyQuotaService.useQuota(useQuotaReqList);
                if (result1 == null || !result1.isSuccess()){
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
            //立即打印收据 -> 返回收据ID
            return Result.success(receipt.getId());
        }
        //对接财务认款
        Result result = iFinanceBillService.addCollection(addListReq);
        if (result == null || !result.isSuccess()){
            throw new BusinessException(SystemError.SYS_437);
        }
        //新增财务挂账使用记录
        if (useQuotaReqList.size() > 0 && collectWay != 3){
            Result result1 = financeOnAccountCurrencyQuotaService.useQuota(useQuotaReqList);
            if (result1 == null || !result1.isSuccess()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        return Result.success(null);
    }

    /**
     * 封装财务挂账使用记录
     *
     *
     * @param touristInfo
     * @param order
     * @param collection
     * @param bigClientId
     * @param bigClientName
     * @param collectWay
     * @param userId
     * @return
     */
    private UseQuotaReq packOnAccountUsageAddReq(SeriesOrderTouristInfo touristInfo, SeriesOrder order, SeriesOrderCollection collection, Long bigClientId, String bigClientName, int collectWay, Long userId) {
        UseQuotaReq req = new UseQuotaReq();
        req.setUserId(userId);
        req.setAccountType(collectWay);
        if (collectWay == 1){
            req.setAccountId(bigClientId);
        }else if (collectWay == 2){
            req.setDeptId(bigClientId);
        }
        req.setAmount(collection.getCurrencyPaidInAmount());
        req.setBigClientName(bigClientName);
        req.setCollectionTypeId(collection.getCollectionTypeId());
        req.setCollectionTypeName(collection.getCollectionType());
        req.setCollectionWayId(collection.getCollectionWayId());
        req.setCollectionWayName(collection.getCollectionWay());
        req.setBillNumber(collection.getCollectionNumber());
        req.setBusinessType(SystemBusinessType.OUTBOUND_TRAVEL.getCode());
        req.setCollectionTime(collection.getGmtCreate());
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(collection.getCollectionVoucherJson())){
            List<FileJson> fileJsons = JSON.parseArray(collection.getCollectionVoucherJson(), FileJson.class);
            req.setCollectionVoucherJson(fileJsons);
        }
        req.setCurrencyId(collection.getCurrencyTypeId());
        req.setCurrencyName(collection.getCurrencyType());
        req.setExchangeRate(collection.getExchangeRate().doubleValue());
        req.setContactMobile(touristInfo.getMobile());
        req.setTouristName(touristInfo.getCnFullname()==null?touristInfo.getEnFullname():touristInfo.getCnFullname());
        req.setTouristSource(order.getCustomerType());
        req.setSaleOrderId(order.getId());
        req.setSaleOrderNumber(order.getOrderNumber());
        req.setProductId(order.getScheduleId());
        SeriesTripScheduleDTO tripSchedule = iSeriesTripScheduleService.getTripScheduleId(order.getScheduleId());
        if (tripSchedule != null){
            req.setProductName(tripSchedule.getSeriesTripScheduleDataDTO().getTitle());
            req.setTripNumber(tripSchedule.getTripNumber());
            List<String> resourceInfo = new ArrayList<>();
            resourceInfo.add(tripSchedule.getSeriesTripScheduleDataDTO().getTitle());
            req.setResourceInfo(resourceInfo);
        }
        req.setSaleUserId(order.getId());
        UserDTO userDTO = iSysUserService.queryCacheUser(order.getCreateId());
        if (userDTO != null){
            req.setSaleUserName(userDTO.getFullName());
        }
        return req;
    }


    /**
     * 更新关联收款记录是否开收据状态
     *
     * @param collectionIdList
     * @param userId
     */
    @Override
    public void batchUpdateIsPrint(List<Long> collectionIdList, Long userId) {
        seriesOrderCollectionMapper.updateByIdList(collectionIdList,userId);
    }

    /**
     * 调整项目
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result adjustProject(CustomOrderAdjustProjectReq req) {
        //返回数据
        List<Long> result = new ArrayList<>();
        //查询订单统计
        QueryWrapper<SeriesOrderAmountStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",req.getOrderId());
        SeriesOrderAmountStatistics statistics = seriesOrderAmountStatisticsMapper.selectOne(queryWrapper);
        if (statistics == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        List<SeriesOrderTouristFeeAdjust> feeAdjustList = new ArrayList<>();
        List<Long> touristList = req.getIdList();



        //订单调整总费用
        BigDecimal totalAddAmount = BigDecimal.ZERO;
        BigDecimal totalReduceAmount = BigDecimal.ZERO;
        //旅客签证列表
        List<SeriesOrderTouristVisa> touristVisaList = new ArrayList<>();
        for (Long touristId : touristList){

            SeriesOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(touristId);
            if (touristInfo == null || Objects.equals(touristInfo.getIsDeleted(),NumberConstant.ONE.getValue())){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
            }
            //清空旧数据
       //     seriesOrderTouristFeeAdjustMapper.cleanByTourist(req.getOrderId(),touristId,req.getUserId());
            //旅客调整总费用
            BigDecimal touristAddAmount = BigDecimal.ZERO;
            BigDecimal touristReduceAmount = BigDecimal.ZERO;
            //增减团费
            List<FeeAdjustReq> feeAdjustIdList = req.getFeeAdjustList();
            if (feeAdjustIdList != null && feeAdjustIdList.size() > 0){
                for (FeeAdjustReq adjustReq : feeAdjustIdList){
                    //判断是否设置过该费用
                    if (checkFeeAdjust(req.getOrderId(),touristId,adjustReq.getMainDataId(),1)){
                        //封装调整费用属性
                        SeriesOrderTouristFeeAdjust feeAdjust = saveTouristFeeAdjustParam(req.getOrderId(),req.getUserId(),1,touristId,
                                adjustReq.getProjectName(), adjustReq.getAdjustType(),adjustReq.getCostAmount(),adjustReq.getMainDataId());
                        feeAdjustList.add(feeAdjust);
                        result.add(feeAdjust.getId());
                        if (adjustReq.getAdjustType().intValue() == NumberConstant.ONE.getValue()){
                            touristAddAmount = touristAddAmount.add(adjustReq.getCostAmount());
                        }else{
                            touristReduceAmount = touristReduceAmount.add(adjustReq.getCostAmount());
                        }
                    }
                }
            }
            //签证
            List<VisaReq> visaList = req.getVisaIdList();
            if (visaList != null && visaList.size() > 0) {
                for (VisaReq visaReq : visaList) {
                    //判断是否设置过该费用
                    if (checkFeeAdjust(req.getOrderId(),touristId,visaReq.getVisaId(),2)){
                        SeriesOrderTouristFeeAdjust feeAdjust = saveTouristFeeAdjustParam(req.getOrderId(),req.getUserId(),2,touristId,
                                visaReq.getName(), 1,visaReq.getAmount(),visaReq.getVisaId());
                        feeAdjustList.add(feeAdjust);
                        result.add(feeAdjust.getId());
                        touristAddAmount = touristAddAmount.add(visaReq.getAmount());
                        //新增旅客签证记录
                        SeriesOrderTouristVisa visa = new SeriesOrderTouristVisa();
                        visa.setId(SnowflakeIdWorker.nextId());
                        visa.setOrderId(req.getOrderId());
                        visa.setTouristId(touristId);
                        visa.setVisaAmount(visaReq.getAmount());
                        visa.setCollectionStatus(1);
                        visa.setNeedSupplyInfo(0);
                        visa.setSignOutStatus(3);
                        touristVisaList.add(visa);
                    }
                }
            }
            //更改资料
            List<ChangeRuleReq> ruleList = req.getRuleList();
            if (ruleList != null && ruleList.size() > 0){
                for (ChangeRuleReq ruleReq : ruleList){
                    //判断是否设置过该费用
                    if (checkFeeAdjust(req.getOrderId(),touristId,ruleReq.getMainDataId(),3)){
                        SeriesOrderTouristFeeAdjust feeAdjust = saveTouristFeeAdjustParam(req.getOrderId(),req.getUserId(),3,touristId,
                                ruleReq.getName(), 1,ruleReq.getAmount(),ruleReq.getMainDataId());
                        feeAdjustList.add(feeAdjust);
                        result.add(feeAdjust.getId());
                        touristAddAmount = touristAddAmount.add(ruleReq.getAmount());
                    }
                }
            }
            //统计订单费用
            totalAddAmount = totalAddAmount.add(touristAddAmount);
            totalReduceAmount = totalReduceAmount.add(totalReduceAmount);
            //更新旅客金额统计
            BigDecimal touristAmount = BigDecimal.ZERO;
            if (touristAddAmount.compareTo(touristReduceAmount) > 0){
                //增加费用
                touristAmount = touristAddAmount.subtract(touristReduceAmount);
                touristInfo.setAdjustmentCost(touristInfo.getAdjustmentCost().add(touristAmount));
                touristInfo.setTotalReceivables(touristInfo.getTotalReceivables().add(touristAmount));
                touristInfo.setRemainingReceivables(touristInfo.getRemainingReceivables().add(touristAmount));
            }else if (touristAddAmount.compareTo(touristReduceAmount) < 0){
                //减少费用
                touristAmount = touristReduceAmount.subtract(touristAddAmount);
                touristInfo.setAdjustmentCost(touristInfo.getAdjustmentCost().subtract(touristAmount));
                touristInfo.setTotalReceivables(touristInfo.getTotalReceivables().subtract(touristAmount));
                touristInfo.setRemainingReceivables(touristInfo.getRemainingReceivables().subtract(touristAmount));
            }
            touristInfo.setModifiedId(req.getUserId());
            int update = orderTouristInfoMapper.updateById(touristInfo);
            if (update <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //一个旅客只能调整一次调整项目费用
        //查出当前list用户下的调整费用订单
        List<SeriesOrderTouristFeeAdjust> list = seriesOrderTouristFeeAdjustMapper.getOrderTouristFeeByAdjustIds(touristList,req.getOrderId());
        for (int i = 0; i < feeAdjustList.size(); i++) {
            SeriesOrderTouristFeeAdjust seriesOrderTouristFeeAdjust = feeAdjustList.get(i);
            for (int j = 0; j < list.size(); j++) {
                int num =0;
                if(!org.springframework.util.StringUtils.isEmpty(seriesOrderTouristFeeAdjust.getOrderId()) && !org.springframework.util.StringUtils.isEmpty(list.get(j).getOrderId())){
                    if(seriesOrderTouristFeeAdjust.getOrderId().longValue() == list.get(j).getOrderId().longValue()){
                        num++;
                    }
                }
                if(!org.springframework.util.StringUtils.isEmpty(seriesOrderTouristFeeAdjust.getAdjustType()) && !org.springframework.util.StringUtils.isEmpty(list.get(j).getAdjustType())){
                    if(seriesOrderTouristFeeAdjust.getAdjustType().intValue() == list.get(j).getAdjustType().intValue()){
                        num++;
                    }
                }
                if(!org.springframework.util.StringUtils.isEmpty(seriesOrderTouristFeeAdjust.getTouristId()) && !org.springframework.util.StringUtils.isEmpty(list.get(j).getTouristId())){
                    if(seriesOrderTouristFeeAdjust.getTouristId().longValue() == list.get(j).getTouristId().longValue()){
                        num++;
                    }
                }
                if(!org.springframework.util.StringUtils.isEmpty(seriesOrderTouristFeeAdjust.getPlusType()) && !org.springframework.util.StringUtils.isEmpty(list.get(j).getPlusType())){
                    if(seriesOrderTouristFeeAdjust.getPlusType().intValue() == list.get(j).getPlusType().intValue()){
                        num++;
                    }
                }
                if(num > 3){
                    feeAdjustList.remove(i);
                    i--;
                }
            }
        }
        if (feeAdjustList.size() > 0){
            //批量新增
            Integer batch = seriesOrderTouristFeeAdjustMapper.insertBatchSomeColumn(feeAdjustList);
            if (batch < feeAdjustList.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //批量新增旅客签证记录
        if (touristVisaList.size() > 0){
            Integer batch = orderTouristVisaMapper.insertBatchSomeColumn(touristVisaList);
            if (batch < touristVisaList.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //更新订单统计
        BigDecimal orderAmount = BigDecimal.ZERO;
        if (totalAddAmount.compareTo(totalReduceAmount) > 0){
            //增加费用
            orderAmount = totalAddAmount.subtract(totalReduceAmount);
            statistics.setAdjustmentCost(statistics.getAdjustmentCost().add(orderAmount));
            statistics.setTotalReceivables(statistics.getTotalReceivables().add(orderAmount));
            statistics.setRemainingReceivables(statistics.getRemainingReceivables().add(orderAmount));
        }else if (totalAddAmount.compareTo(totalReduceAmount) < 0){
            //减少费用
            orderAmount = totalReduceAmount.subtract(totalAddAmount);
            statistics.setAdjustmentCost(statistics.getAdjustmentCost().subtract(orderAmount));
            statistics.setTotalReceivables(statistics.getTotalReceivables().subtract(orderAmount));
            statistics.setRemainingReceivables(statistics.getRemainingReceivables().subtract(orderAmount));
        }
        //更新订单金额统计
        int update = seriesOrderAmountStatisticsMapper.updateById(statistics);
        if (update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(result);
    }

    /**
     * 计算港币收款金额
     *
     * @param req
     * @return
     */
    @Override
    public Result getHkdAmount(List<GetHkdAmountReq> req) {
        BigDecimal totalHkdAmount = BigDecimal.ZERO;
        for (GetHkdAmountReq item : req){
            BigDecimal hkdAmount = iMainDataCurrencyService.getHkdAmount(item.getCurrencyId(), item.getAmount());
            if (hkdAmount != null){
                totalHkdAmount = totalHkdAmount.add(hkdAmount);
            }
        }
        return Result.success(totalHkdAmount);
    }

    /**
     * 封装调整费用属性
     * @return
     */
    private SeriesOrderTouristFeeAdjust saveTouristFeeAdjustParam(Long orderId, Long userId, int adjustType, Long touristId,
                                                                      String name,int plusType,BigDecimal amount,Long relationId) {
        SeriesOrderTouristFeeAdjust feeAdjust = new SeriesOrderTouristFeeAdjust();
        feeAdjust.setId(SnowflakeIdWorker.nextId());
        feeAdjust.setOrderId(orderId);
        feeAdjust.setAdjustType(adjustType);
        feeAdjust.setTouristId(touristId);
        feeAdjust.setName(name);
        feeAdjust.setPlusType(plusType);
        feeAdjust.setAmount(amount);
        feeAdjust.setRelationId(relationId);
        feeAdjust.setCreateId(userId);
        feeAdjust.setGmtCreate(LocalDateTime.now());
        feeAdjust.setIsDeleted(0);
        return feeAdjust;
    }

    /**
     * 判断是否设置过该费用
     * @param orderId
     * @param touristId
     * @param mainDataId
     * @param adjustType
     * @return
     */
    private boolean checkFeeAdjust(Long orderId, Long touristId, Long mainDataId,Integer adjustType) {
        QueryWrapper<SeriesOrderTouristFeeAdjust> feeAdjustWrapper = new QueryWrapper<>();
        feeAdjustWrapper.eq("order_id",orderId);
        feeAdjustWrapper.eq("tourist_id",touristId);
        feeAdjustWrapper.eq("relation_id",mainDataId);
    //    feeAdjustWrapper.eq("adjust_type",adjustType);
        feeAdjustWrapper.eq("is_deleted",0);
        SeriesOrderTouristFeeAdjust feeAdjust = seriesOrderTouristFeeAdjustMapper.selectOne(feeAdjustWrapper);
        if (feeAdjust == null){
            return true;
        }
        return false;
    }

    /**
     * 封装财务认款请求参数
     * @param item
     * @param collection
     * @param tripSchedule
     * @param order
     * @param userId
     * @return
     */
    private BillAddCollectionReq packBillAddCollectionReq(CustomOrderCollectionAddItemReq item, SeriesOrderCollection collection, SeriesTripScheduleDTO tripSchedule, SeriesOrder order, Long userId) {
        BillAddCollectionReq addReq = new BillAddCollectionReq();
        addReq.setBillNumber(collection.getCollectionNumber());
        addReq.setBusinessType(SystemBusinessType.OUTBOUND_TRAVEL.getCode());
        addReq.setCollectionWayId(item.getCollectionWayId());
        addReq.setCollectionWayName(item.getCollectionWay());
        addReq.setCollectionTypeId(item.getCollectionTypeId());
        addReq.setCollectionTypeName(item.getCollectionType());
        addReq.setCollectionAmount(collection.getPaidInAmount());
        addReq.setCurrencyId(item.getCurrencyTypeId());
        addReq.setCurrencyName(item.getCurrencyType());
        addReq.setExchangeRate(item.getExchangeRate());
        addReq.setCollectionTime(collection.getGmtCreate());
        addReq.setCollectionVoucherJsonList(item.getCollectionVoucherJsonList());
        addReq.setSaleOrderNumber(order.getOrderNumber());
        addReq.setSaleOrderId(order.getId());
        addReq.setProductNumber(tripSchedule.getTripNumber());
        addReq.setProductName(tripSchedule.getSeriesTripScheduleDataDTO().getTitle());
        List<String> resourceInfo = new ArrayList<>();
        resourceInfo.add(tripSchedule.getSeriesTripScheduleDataDTO().getTitle());
        addReq.setResourceInfo(resourceInfo);
        addReq.setSaleUserId(collection.getCreateId());
        UserDTO userDTO = iSysUserService.queryCacheUser(collection.getCreateId());
        addReq.setSaleUserName(userDTO.getFullName());
        addReq.setSaleDeptId(userDTO.getDeptId());
        addReq.setUserId(userId);
        addReq.setScheduleId(tripSchedule.getId());
        addReq.setTouristSource(order.getCustomerType());
        if (Objects.equals(order.getCustomerType(),2)){
            addReq.setBigClientId(order.getBigClientId());
            addReq.setBigClientName(order.getBigClientName());
        }
        return addReq;
    }

    /**
     * 计算
     */
 //   @Override
    public Result<SeriesOrderCollectionCalculationDTO> calculation2(SeriesOrderCollectionCalculationReq req, TokenUser currentUser) {
        if (req.getItems().size() <= 0) {
            return Result.failed(SystemError.SYS_409);
        }

        MainDataCurrencyUpdateStatusReq hkdReq = new MainDataCurrencyUpdateStatusReq();
        hkdReq.setId(CurrencyIdCode.HKD.getCode());
        Result<MainDataCurrencyQueryDTO> hkdResult = iMainDataCurrencyService.query(hkdReq);
        if (!hkdResult.isSuccess() || hkdResult.getData() == null) {
            return Result.failed(SystemError.SYS_411);
        }
        MainDataCurrencyQueryDTO hkdDTO = hkdResult.getData();

        //总收款金额
        BigDecimal totalPaidInAmount = new BigDecimal(0);
        //总银行优惠基准金额
        BigDecimal totalTouristAmount = new BigDecimal(0);

        List<SeriesOrderCollectionCalculationItemDTO> itemList = new ArrayList<>();
        for (SeriesOrderCollectionCalculationItemReq item : req.getItems()) {
            //排除银行优惠计算
            if (Objects.equals(CollectionRefundWayIdCode.BANK_PREFERENCE.getCode(), item.getCollectionWayId())) {
                continue;
            }
            //收款金额
            BigDecimal paidInAmount = new BigDecimal(0);
            SeriesOrderCollectionCalculationItemDTO calculationItem = EntityUtil.copy(item, SeriesOrderCollectionCalculationItemDTO.class);
            if (Objects.equals(CurrencyIdCode.HKD.getCode(), item.getCurrencyTypeId())) {
                calculationItem.setCurrencyType(hkdDTO.getCurrencyName());
                calculationItem.setCurrencyTypeId(CurrencyIdCode.HKD.getCode());
                calculationItem.setCurrencyCode(hkdDTO.getCurrencyCode());
                paidInAmount = item.getCurrencyPaidInAmount();
            } else {
                MainDataCurrencyUpdateStatusReq currencyUpdateStatusReq = new MainDataCurrencyUpdateStatusReq();
                currencyUpdateStatusReq.setId(item.getCurrencyTypeId());
                Result<MainDataCurrencyQueryDTO> currencyQueryDTOResult = iMainDataCurrencyService.query(currencyUpdateStatusReq);
                if (!currencyQueryDTOResult.isSuccess() || currencyQueryDTOResult.getData() == null) {
                    return Result.failed(SystemError.SYS_411);
                }
                MainDataCurrencyQueryDTO currencyQueryDTO = currencyQueryDTOResult.getData();
                calculationItem.setCurrencyType(currencyQueryDTO.getCurrencyName());
                calculationItem.setCurrencyTypeId(item.getCurrencyTypeId());
                calculationItem.setCurrencyCode(currencyQueryDTO.getCurrencyCode());
                //收款金额 港幣金額=其他貨幣金額×對應的門市匯率
                paidInAmount = item.getCurrencyPaidInAmount().multiply(currencyQueryDTO.getMarketExchangeRate());
            }

            QueryWrapper<SeriesOrderTouristInfo> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getOrderId, req.getOrderId());
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getId, item.getTouristId());
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getIsDeleted, IsDeletedCode.NO.getCode());
            SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectOne(queryWrapper2);
            if (touristInfo == null) {
                return Result.failed(SystemError.SYS_411);
            }

            QueryWrapper<SeriesOrderTouristFeeAdjust> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getTouristId, item.getTouristId());
            queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getAdjustType, AdjustTypeCode.ADJUST.getCode());
            queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getIsDeleted, IsDeletedCode.NO.getCode());
            List<SeriesOrderTouristFeeAdjust> feeAdjustList = seriesOrderTouristFeeAdjustMapper.selectList(queryWrapper);
            BigDecimal touristAmount = touristInfo.getGroupFee();
            for (SeriesOrderTouristFeeAdjust feeAdjust : feeAdjustList) {
                if (Objects.equals(feeAdjust.getPlusType(), PlusTypeCode.PLUS.getCode())) {
                    touristAmount = touristAmount.add(feeAdjust.getAmount());
                } else if (Objects.equals(feeAdjust.getPlusType(), PlusTypeCode.SUBTRACT.getCode())) {
                    touristAmount = touristAmount.subtract(feeAdjust.getAmount());
                }
            }

            //总收款金额
            totalPaidInAmount = totalPaidInAmount.add(paidInAmount);

            itemList.add(calculationItem);

            //总银行优惠基准金额
            totalTouristAmount = totalTouristAmount.add(touristAmount);
        }

        //总银行优惠金额
        BigDecimal totalBankPreferenceAmount = new BigDecimal(0);
        //银行优惠
        List<SeriesOrderCollectionCalculationItemDTO> bankPreferenceList = new ArrayList<>();
        if (req.getBankPreferenceId() != null) {
            SeriesOrderCollectionCalculationItemReq firstItem = req.getItems().get(0);
            OperateBankConformQueryReq bankPreferenceQueryReq = new OperateBankConformQueryReq();
            bankPreferenceQueryReq.setId(req.getBankPreferenceId());
            bankPreferenceQueryReq.setBusinessType(BusinessTypeCode.GROUP.getCode());
            bankPreferenceQueryReq.setCardNumber(firstItem.getPayer());
            bankPreferenceQueryReq.setRelationId(req.getScheduleId());
            bankPreferenceQueryReq.setUserId(currentUser.getId());
            bankPreferenceQueryReq.setTotalPaidIn(totalTouristAmount);
            bankPreferenceQueryReq.setChannelId(OrderSource.CPM.getCode().longValue());
            SeriesOrder dbOrder = seriesOrderMapper.selectById(req.getOrderId());
            if (dbOrder == null) {
                return Result.failed(SystemError.SYS_411);
            }
            CrmMemberQueryReq crmMemberQueryReq = new CrmMemberQueryReq(QueryType.PHONE.getCode(), dbOrder.getMemberMobile(), null);
            CrmAccountDTO crmAccountDTO = iCrmMemberService.queryAccountDetail(crmMemberQueryReq);
            if (crmAccountDTO == null) {
                return Result.failed(SystemError.SYS_411);
            }
            bankPreferenceQueryReq.setDiscountObjectId(crmAccountDTO.getType().longValue());
            Result<OperateBankPreferenceQueryDTO> preferenceQueryDTOResult = iOperateBankPreferenceService.queryConform(bankPreferenceQueryReq);
            if (preferenceQueryDTOResult != null && preferenceQueryDTOResult.isSuccess() &&
                    preferenceQueryDTOResult.getData() != null) {

                OperateBankPreferenceQueryDTO preferenceQueryDTOResultData = preferenceQueryDTOResult.getData();
                if (Objects.equals(preferenceQueryDTOResultData.getDiscountType(), DiscountType.SUBTRACT.getCode())) {
                    if (totalTouristAmount.compareTo(preferenceQueryDTOResultData.getFullAmount()) >= 0) {
                        BigDecimal bankPreference = totalTouristAmount.subtract(preferenceQueryDTOResultData.getReductionAmount());
                        totalBankPreferenceAmount = totalBankPreferenceAmount.add(bankPreference);
                    }
                } else if (Objects.equals(preferenceQueryDTOResultData.getDiscountType(), DiscountType.DISCOUNT.getCode())) {
                    BigDecimal bankPreference = totalTouristAmount.subtract(totalTouristAmount.multiply(
                            BigDecimal.valueOf(preferenceQueryDTOResultData.getDiscountPercent())));
                    if (bankPreference.compareTo(preferenceQueryDTOResultData.getMaxDiscount()) > 0) {
                        totalBankPreferenceAmount = totalBankPreferenceAmount.add(preferenceQueryDTOResultData.getMaxDiscount());
                    } else {
                        totalBankPreferenceAmount = totalBankPreferenceAmount.add(bankPreference);
                    }
                }

                int size = req.getItems().size();
                BigDecimal[] bankPreferenceAmount = totalBankPreferenceAmount.divideAndRemainder(new BigDecimal(size));

                MainDataFieldDataDTO collectionTypeDTO = iMainDataFieldDataService.queryFieldData(
                        CollectionTypeIdCode.FULL.getCode());
                if (collectionTypeDTO == null) {
                    return Result.failed(SystemError.SYS_411);
                }
                MainDataPaymentRefundTypeIdReq bankReq = new MainDataPaymentRefundTypeIdReq();
                bankReq.setId(CollectionRefundWayIdCode.BANK.getCode());
                MainDataPaymentRefundTypeDTO bankDTO = iMainDataPaymentRefundTypeService.query(bankReq);
                if (bankDTO == null) {
                    return Result.failed(SystemError.SYS_411);
                }
                MainDataPaymentRefundTypeIdReq bankPreferenceReq = new MainDataPaymentRefundTypeIdReq();
                bankPreferenceReq.setId(CollectionRefundWayIdCode.BANK_PREFERENCE.getCode());
                MainDataPaymentRefundTypeDTO bankPreferenceDTO = iMainDataPaymentRefundTypeService.query(bankPreferenceReq);
                if (bankPreferenceDTO == null) {
                    return Result.failed(SystemError.SYS_411);
                }
                for (int i = 0; i < size; i++) {
                    SeriesOrderCollectionCalculationItemReq itemReq = req.getItems().get(i);
                    itemReq.setCollectionTypeId(collectionTypeDTO.getId());
                    itemReq.setCollectionType(collectionTypeDTO.getFieldValue());
                    itemReq.setCollectionWayId(bankDTO.getId());
                    itemReq.setCollectionWay(bankDTO.getPaymentRefundName());

                    SeriesOrderCollectionCalculationItemDTO bankPreferenceItem = EntityUtil.copy(itemReq,
                            SeriesOrderCollectionCalculationItemDTO.class);
                    bankPreferenceItem.setCurrencyType(hkdDTO.getCurrencyName());
                    bankPreferenceItem.setCurrencyTypeId(CurrencyIdCode.HKD.getCode());
                    bankPreferenceItem.setCurrencyCode(hkdDTO.getCurrencyCode());
                    bankPreferenceItem.setCollectionTypeId(collectionTypeDTO.getId());
                    bankPreferenceItem.setCollectionType(collectionTypeDTO.getFieldValue());
                    bankPreferenceItem.setCollectionWayId(bankPreferenceDTO.getId());
                    bankPreferenceItem.setCollectionWay(bankPreferenceDTO.getPaymentRefundName());
                    bankPreferenceItem.setCurrencyPaidInAmount(bankPreferenceAmount[0]);

                    if (i == size - 1 && bankPreferenceAmount[1].compareTo(new BigDecimal(0)) > 0) {
                        bankPreferenceItem.setCurrencyPaidInAmount(bankPreferenceItem.getCurrencyPaidInAmount().add(bankPreferenceAmount[i]));
                    }

                    bankPreferenceItem.setPayer(null);
                    bankPreferenceItem.setRemark(null);
                    bankPreferenceItem.setCollectionVoucherNum(null);
                    bankPreferenceItem.setCollectionVoucherJsonList(null);

                    if (bankPreferenceItem.getCurrencyPaidInAmount().compareTo(new BigDecimal(0)) == 0) {
                        continue;
                    }
                    bankPreferenceList.add(bankPreferenceItem);
                }
            }
        }

        itemList.addAll(bankPreferenceList);

        SeriesOrderCollectionCalculationDTO model = new SeriesOrderCollectionCalculationDTO();
        model.setItemList(itemList);
        model.setTotalPaidInAmount(totalPaidInAmount);
        model.setTotalBankPreferenceAmount(totalBankPreferenceAmount);
        return Result.success(model);
    }

    /**
     * 列表
     */
    @Override
    public List<SeriesOrderCollectionListDTO> list(SeriesOrderTouristInfoDetailReq req) {
        List<SeriesOrderCollectionListDTO> reciveList = seriesOrderCollectionMapper.reciveListByTourist(req.getId());
        if (CollectionUtils.isNotEmpty(reciveList)){
            for (SeriesOrderCollectionListDTO collectionDTO : reciveList) {
                try {
                    if (collectionDTO.getCreateId() != null){
                        UserDTO userDTO = iSysUserService.queryCacheUser(collectionDTO.getCreateId());
                        if (userDTO != null){
                            collectionDTO.setReciveName(userDTO.getFullName());
                            collectionDTO.setReciveDept(userDTO.getDept());
                        }
                    }
                }catch (Exception e){
                    throw new BusinessException(SystemError.SYS_417);
                }
            }
            return reciveList;
        }
        return null;
    }


    /**
     * 确认
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result confirm(SeriesOrderCollectionConfirmReq req) {
        QueryWrapper<SeriesOrderCollection> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(SeriesOrderCollection::getId, req.getId());
        queryWrapper1.lambda().eq(SeriesOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode());
        SeriesOrderCollection dbCollection = seriesOrderCollectionMapper.selectOne(queryWrapper1);
        if (dbCollection == null || !Objects.equals(dbCollection.getStatus(), SeriesOrderCollectionStatusCode.REJECT.getCode())) {
            return Result.failed(SeriesOrderErrorCode.STATUS_ERROR);
        }
        dbCollection.setModifiedId(req.getUserId());
        dbCollection.setRejectMsg(null);
        dbCollection.setStatus(SeriesOrderCollectionStatusCode.APPROVAL.getCode());
        boolean update = updateById(dbCollection);
        if (!update){
            throw new BusinessException(SystemError.SYS_408);
        }

        //同步财务状态
        BillOperateRefundReq billOperateRefundReq = new BillOperateRefundReq();
        billOperateRefundReq.setBillNumber(dbCollection.getCollectionNumber());
        billOperateRefundReq.setBusinessType(SystemBusinessType.OUTBOUND_TRAVEL.getCode());
        billOperateRefundReq.setUserId(req.getUserId());
        Result result = iFinanceBillService.reConfirm(billOperateRefundReq);
        if (result == null || result.getCode() != 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success();
    }

    /**
     * 可购买保险列表
     *
     * @param req
     * @return
     */
    @Override
    public Result<List<OrderInsuranceDTO>> insuranceList(CustomOrderInsuranceListReq req) {
        List<OrderInsuranceDTO> list = new ArrayList<>();
        SeriesTripScheduleDTO tripScheduleDTO = iSeriesTripScheduleService.getTripScheduleId(req.getScheduleId());
        if (tripScheduleDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        SeriesTripScheduleDataDTO seriesTripScheduleDataDTO = tripScheduleDTO.getSeriesTripScheduleDataDTO();
        if (seriesTripScheduleDataDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        TripBasicInformationDTO tripBasicInformationDTO = iSeriesTripService.basicInformation(seriesTripScheduleDataDTO.getTripId());
        if (tripBasicInformationDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        SeriesTripReq seriesTripReq = tripBasicInformationDTO.getSeriesTripReq();
        if (seriesTripReq == null || CollectionUtils.isEmpty(seriesTripReq.getInsuranceList())) {
            return Result.failed(SeriesOrderErrorCode.TRIP_NOT_INSURANCE_ERROR);
        }
        //旅客信息
        int childNum = 0;
        int adultNum = 0;
        List<Long> touristList = req.getTouristList();
        for (Long touristId : touristList){
            SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectById(touristId);
            if (touristInfo != null){
                Integer age = DateUtil.getAge(touristInfo.getBirthday());
                String ageType = PacificUtil.getAgeType(age);
                if (PacificAgeTypeCode.CHILD.getCode().equals(ageType)){
                    childNum++;
                }else{
                    adultNum++;
                }
            }
        }
        List<TripInsuranceReq> insuranceList = seriesTripReq.getInsuranceList();
        //获取报价
        try {
            for (TripInsuranceReq insuranceDTO : insuranceList){
                InsuranceDTO detail = iInsuranceService.detail(insuranceDTO.getInsuranceId());
                if (detail != null){
                    OrderInsuranceDTO dto = EntityUtil.copy(detail,OrderInsuranceDTO.class);
                    OfferDTO offerDTO = insuranceOffer(req.getBeginDate(), req.getEndDate(), detail.getRationType(), detail.getApiCode(), childNum, adultNum,insuranceDTO.getInsuranceId());
                    if (offerDTO != null){
                        dto.setTotalAmount(offerDTO.getPremium());
                        dto.setChildNum(childNum);
                        dto.setAdultNum(adultNum);
                    }
                    list.add(dto);
                }
            }
        }catch (Exception e){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4026);
        }
        return Result.success(list);
    }

    /**
     * 購買保險
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<OrderBuyInsuranceDTO> buyInsurance(CustomOrderBuyInsuranceReq req) {
        OrderBuyInsuranceDTO orderBuyInsuranceDTO = new OrderBuyInsuranceDTO();
        List<BuyInsuranceDTO> dtoList = new ArrayList<>();
        SeriesOrder order = seriesOrderMapper.selectById(req.getOrderId());
        if (order == null || Objects.equals(order.getIsDeleted(), NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        List<SeriesOrderInsurancePriceTourist> list = new ArrayList<>();
        //获取保险详情
        InsuranceDTO insuranceDTO = null;
        try {
            insuranceDTO = iInsuranceService.detail(req.getId());
        }catch (Exception e){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4026);
        }
        if (insuranceDTO == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4028);
        }
        //保险
        SeriesOrderInsurance insurance = EntityUtil.copy(req,SeriesOrderInsurance.class);
        insurance.setId(SnowflakeIdWorker.nextId());
        insurance.setOrderId(req.getOrderId());
        insurance.setScheduleId(order.getScheduleId());
        String insuranceNumber = getInsuranceNumber(req.getUserId());
        insurance.setInsuranceNumber(insuranceNumber);
        insurance.setInsuranceRecordId(insuranceDTO.getId());
        insurance.setMainDataId(req.getId());
        insurance.setName(insuranceDTO.getName());
        insurance.setApiCode(insuranceDTO.getApiCode());
        insurance.setRationType(insuranceDTO.getRationType());
        insurance.setInsuranceCarriers(insuranceDTO.getCompanyName());
        insurance.setCurrencyId(CurrencyIdCode.HKD.getCode());
        insurance.setCurrency(CurrencyIdCode.HKD.getMsg());
        insurance.setIsPay(0);
        insurance.setCreateId(req.getUserId());
        insurance.setIsDeleted(0);
        insurance.setIsPrint(0);
        //保险报价
        OfferDTO offerDTOS = insuranceOffer(req.getBeginDate(),req.getEndDate(),insuranceDTO.getRationType(),
                insuranceDTO.getApiCode(),req.getChildNum(),req.getAdultNum(),insuranceDTO.getId());
        insurance.setTotalAmount(offerDTOS.getPremium());
        List<Long> touristList = req.getTouristList();
        insurance.setPeopleNumber(touristList.size());
        //保险单价（各传1人获取单价）
        BigDecimal childPrice = BigDecimal.ZERO;
        BigDecimal adultPrice = BigDecimal.ZERO;
        if (req.getChildNum() > 0){
            OfferDTO offerChild = insuranceOffer(req.getBeginDate(),req.getEndDate(),insuranceDTO.getRationType(),
                    insuranceDTO.getApiCode(),1,0,insuranceDTO.getId());
            childPrice = offerChild.getPremium();
        }
        if (req.getAdultNum() > 0){
            OfferDTO offerAdult = insuranceOffer(req.getBeginDate(),req.getEndDate(),insuranceDTO.getRationType(),
                    insuranceDTO.getApiCode(),0,1,insuranceDTO.getId());
            adultPrice = offerAdult.getPremium();
        }
        //保险价格
        for (Long touristId : touristList){
            SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectById(touristId);
            if (touristInfo == null || Objects.equals(touristInfo.getIsDeleted(),NumberConstant.ONE.getValue()) || Objects.equals(touristInfo.getBuyInsurance(),1)){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4029);
            }
            //    touristInfo.setBuyInsurance(1);
            touristInfo.setInsuranceId(insurance.getId());
            touristInfo.setInsuranceName(insurance.getName());
            touristInfo.setModifiedId(req.getUserId());
            int update = seriesOrderTouristInfoMapper.updateById(touristInfo);
            if (update <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
            SeriesOrderInsurancePriceTourist insurancePriceTourist = new SeriesOrderInsurancePriceTourist();
            insurancePriceTourist.setId(SnowflakeIdWorker.nextId());
            insurancePriceTourist.setInsuranceId(insurance.getId());
            insurancePriceTourist.setOrderId(req.getOrderId());
            insurancePriceTourist.setScheduleId(order.getScheduleId());
            insurancePriceTourist.setTouristId(touristId);
            insurancePriceTourist.setTouristTypeId(touristInfo.getMainDataId());
            int age = touristInfo.getBirthday().until(LocalDate.now()).getYears();
            insurancePriceTourist.setAge(age);
            //获取年龄类型
            String ageType = PacificUtil.getAgeType(age);
            if (PacificAgeTypeCode.CHILD.getCode().equals(ageType)){
                //28:小童,太平保险那边固定的值
                insurancePriceTourist.setAmount(childPrice);
            }else{
                insurancePriceTourist.setAmount(adultPrice);
            }
            insurancePriceTourist.setEnSurname(touristInfo.getEnSurname());
            insurancePriceTourist.setEnName(touristInfo.getEnName());
            insurancePriceTourist.setBirthday(touristInfo.getBirthday());
            insurancePriceTourist.setSex(touristInfo.getGender());
            insurancePriceTourist.setCertificateTypeId(touristInfo.getCertificateTypeId1());
            insurancePriceTourist.setCertificateNumber(touristInfo.getCertificateNumber1());
            list.add(insurancePriceTourist);
            //返回数据
            BuyInsuranceDTO dto = new BuyInsuranceDTO();
            dto.setId(insurancePriceTourist.getId());
            dto.setTouristId(touristId);
            if (StringUtils.isNotBlank(touristInfo.getCnFullname())){
                dto.setTouristName(touristInfo.getCnFullname());
            }else if (StringUtils.isNotBlank(touristInfo.getEnFullname())){
                dto.setTouristName(touristInfo.getEnFullname());
            }
            dto.setCurrencyId(insurance.getCurrencyId());
            dto.setCurrency(insurance.getCurrency());
            dto.setAmount(insurancePriceTourist.getAmount());
            dtoList.add(dto);
        }
        int insert = orderInsuranceMapper.insert(insurance);
        //批量新增
        Integer batch = orderInsurancePriceTouristMapper.insertBatchSomeColumn(list);
        if (insert <= 0 || batch < list.size()){
            throw new BusinessException(SystemError.SYS_437);
        }
        //返回数据
        orderBuyInsuranceDTO.setInsuranceId(insurance.getId());
        orderBuyInsuranceDTO.setList(dtoList);
        return Result.success(orderBuyInsuranceDTO);
    }

    /**
     * 保險收款
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result collectInsurance(CustomOrderCollectInsuranceReq req) {
        SeriesOrder order = seriesOrderMapper.selectById(req.getOrderId());
        if (order == null || Objects.equals(order.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        SeriesTripScheduleDTO tripSchedule = iSeriesTripScheduleService.getTripScheduleId(order.getScheduleId());
        //保单
        SeriesOrderInsurance insurance = orderInsuranceMapper.selectById(req.getInsuranceId());
        if (insurance == null || Objects.equals(insurance.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4023);
        }
        if (insurance.getIsPay().intValue() == NumberConstant.ONE.getValue()){
            //重复收款
            throw new BusinessException(SystemError.CUSTOM_ORDER_4023);
        }
        //判断是否可以收款
        QueryWrapper<SeriesOrderAmountStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SeriesOrderAmountStatistics::getOrderId, req.getOrderId());
        SeriesOrderAmountStatistics statistics = seriesOrderAmountStatisticsMapper.selectOne(queryWrapper);
        //本次收款总金额
        BigDecimal totalReciveAmount = BigDecimal.ZERO;
        for (CustomOrderCollectionAddItemReq item : req.getItems()){
            BigDecimal hkdAmount = iMainDataCurrencyService.getHkdAmount(item.getCurrencyTypeId(), item.getPaidInAmount());
            totalReciveAmount = totalReciveAmount.add(hkdAmount == null?BigDecimal.ZERO:hkdAmount);
        }
       /* if (totalReciveAmount.compareTo(statistics.getRemainingReceivables()) > 0){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4009);
        }*/
        //收据金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<SeriesOrderCollection> collectionList = new ArrayList<>();
        List<SeriesOrderReceiptTourist> receiptTouristList = new ArrayList<>();
        //订单收据
        SeriesOrderReceipt receipt = new SeriesOrderReceipt();
        receipt.setId(SnowflakeIdWorker.nextId());
        receipt.setOrderId(req.getOrderId());
        receipt.setScheduleId(order.getScheduleId());
        receipt.setReceiptAmount(totalReciveAmount);
        //收据单号
        String receiptNumber = getReceiptNumber(req.getUserId());
        receipt.setReceiptNumber(receiptNumber);
        receipt.setReceiptType(2);
        receipt.setCreateTime(LocalDateTime.now());
        receipt.setReceiptStatus(1);
        receipt.setCreateId(req.getUserId());
        receipt.setIsDeleted(0);
        //新增财务认款请求参数
        List<BillAddCollectionReq> addListReq = new ArrayList<>();
        //印花税金额
        BigDecimal stampDutyAmount = BigDecimal.ZERO;
        //调整费用列表
        List<SeriesOrderTouristFeeAdjust> feeAdjustList = new ArrayList<>();
        List<CustomOrderCollectionAddItemReq> itemList = req.getItems();
        for (CustomOrderCollectionAddItemReq itemReq : itemList){
            //计算印花税
            stampDutyAmount = stampDutyAmount.add(itemReq.getPaidInAmount().multiply(new BigDecimal(Constants.STAMP_DUTY_RATIO)));
            //更新旅客金额
            SeriesOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(itemReq.getTouristId());
            if (touristInfo.getRemainingReceivables().compareTo(itemReq.getPaidInAmount()) < 0){
                continue;
            }
            touristInfo.setBuyInsurance(1);
            touristInfo.setTotalReceivables(touristInfo.getTotalReceivables().add(itemReq.getPaidInAmount()));
            touristInfo.setTotalPaidIn(touristInfo.getTotalPaidIn().add(itemReq.getPaidInAmount()));
            //     touristInfo.setRemainingReceivables(touristInfo.getRemainingReceivables().subtract(itemReq.getPaidInAmount()));
            touristInfo.setReceiptedAmount(touristInfo.getReceiptedAmount().add(totalReciveAmount));
            touristInfo.setModifiedId(req.getUserId());
            if (touristInfo.getRemainingReceivables().compareTo(BigDecimal.ZERO) <= 0){
                //已付全款
                touristInfo.setPayStatus(3);
            }
            int update = orderTouristInfoMapper.updateById(touristInfo);
            if (update <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
            //收款记录
            SeriesOrderCollection collection = EntityUtil.copy(itemReq, SeriesOrderCollection.class);
            LocalDateTime now = LocalDateTime.now();
            collection.setId(IdWorker.getId());
            BigDecimal hkdAmount = iMainDataCurrencyService.getHkdAmount(itemReq.getCurrencyTypeId(), itemReq.getPaidInAmount());
            collection.setCurrencyPaidInAmount(itemReq.getPaidInAmount());
            collection.setPaidInAmount(hkdAmount);
            collection.setPayerId(req.getPayerId());
            collection.setGmtCreate(now);
            collection.setIsDeleted(0);
            collection.setCreateId(req.getUserId());
            collection.setIsPos(req.getIsPos());
            //收款单号
            String collectionNumber = StrConstant.SKD.getValue() + DateUtil.fmt(LocalDateTime.now(),"yyMMddHHmmss" + CharUtil.getRandomStr(2));
            collection.setCollectionNumber(collectionNumber);
            collection.setStatus(2);
            collection.setOrderId(req.getOrderId());
            collection.setScheduleId(order.getScheduleId());
            collection.setIsPrint(1);
            collectionList.add(collection);
            //财务认款请求参数
            BillAddCollectionReq addReq = packBillAddCollectionReq(itemReq,collection,tripSchedule,order,req.getUserId());
            addListReq.add(addReq);
            //收据关联旅客
            SeriesOrderReceiptTourist receiptTourist = new SeriesOrderReceiptTourist();
            receiptTourist.setId(SnowflakeIdWorker.nextId());
            receiptTourist.setReceiptId(receipt.getId());
            receiptTourist.setOrderId(req.getOrderId());
            receiptTourist.setTouristId(itemReq.getTouristId());
            receiptTourist.setCreateId(req.getUserId());
            receiptTourist.setReceiptAmount(collection.getPaidInAmount());
            receiptTourist.setIsDeleted(0);
            receiptTouristList.add(receiptTourist);
            totalAmount = totalAmount.add(collection.getPaidInAmount());
            //新增调整费用
            SeriesOrderTouristFeeAdjust feeAdjust = new SeriesOrderTouristFeeAdjust();
            feeAdjust.setId(SnowflakeIdWorker.nextId());
            feeAdjust.setOrderId(order.getId());
            feeAdjust.setAdjustType(4);
            feeAdjust.setTouristId(touristInfo.getId());
            feeAdjust.setName("保险");
            feeAdjust.setPlusType(1);
            feeAdjust.setAmount(collection.getPaidInAmount());
            feeAdjust.setRelationId(collection.getId());
            feeAdjust.setCreateId(req.getUserId());
            feeAdjust.setGmtCreate(now);
            feeAdjust.setIsDeleted(0);
            feeAdjustList.add(feeAdjust);
        }
        //更新订单统计
        statistics.setTotalReceivables(statistics.getTotalReceivables().add(totalAmount));
        statistics.setTotalPaidIn(statistics.getTotalPaidIn().add(totalAmount));
        statistics.setReceiptedAmount(statistics.getReceiptedAmount().add(totalAmount));
        int update1 = seriesOrderAmountStatisticsMapper.updateById(statistics);
        if (update1 <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //收据
        receipt.setReceiptHeader(insurance.getPolicyHolderName());
        receipt.setReceiptAmount(totalAmount);
        receipt.setIncludeTouristNum(itemList.size());
        //新增订单收据
        int insertReceipt = seriesOrderReceiptMapper.insert(receipt);
        //批量新增调整费用
        if (feeAdjustList.size() > 0){
            Integer batch = seriesOrderTouristFeeAdjustMapper.insertBatchSomeColumn(feeAdjustList);
            if (batch < feeAdjustList.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //批量新增收据关联旅客
        if (receiptTouristList.size() > 0){
            Integer batch = seriesOrderReceiptTouristMapper.insertBatchSomeColumn(receiptTouristList);
            if (insertReceipt <= 0 || batch < receiptTouristList.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //批量新增收款
        if (collectionList.size() > 0){
            Integer batch = seriesOrderCollectionMapper.insertBatchSomeColumn(collectionList);
            if (batch < collectionList.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //直接生成保单收据
        ReceiptInsuranceAddReq addReq = EntityUtil.copy(req,ReceiptInsuranceAddReq.class);
        addReq.setCurrency(req.getCurrencyType());
        addReq.setCardNumber(req.getPayer());
        Long insuranceReceiptId = orderReceiptInsuranceService.createInsuranceReceipt(addReq);
        if (insuranceReceiptId == null){
            throw new BusinessException(SystemError.SYS_437);
        }
        //调用保险API
        InsuranceInsuredDTO insuranceInsuredDTO = null;
        //封装参保请求参数
        InsuranceUnderwritingReq insuranceUnderwritingReq = new InsuranceUnderwritingReq();
        List<AcceptUnderReq> acceptReq = packJoinInsuranceReq(insurance);
        insuranceUnderwritingReq.setAcceptReqList(acceptReq);
        insuranceUnderwritingReq.setUserId(req.getUserId());
        insuranceUnderwritingReq.setInsuranceId(insurance.getInsuranceRecordId());
        insuranceUnderwritingReq.setOrderNumber(order.getOrderNumber());
        insuranceUnderwritingReq.setBusinessType(SystemBusinessType.OUTBOUND_CUSTOMIZATION.getCode());
        insuranceUnderwritingReq.setTotalFee(insurance.getTotalAmount());
        try {
            insuranceInsuredDTO = iInsuranceService.sendProposalContent(insuranceUnderwritingReq);
        }catch (Exception e){
            log.error("保险服务报错, error:{}", e.getMessage(), e);
            throw new BusinessException(SystemError.CUSTOM_ORDER_4026);
        }
        List<AcceptDTO> acceptDTOS = insuranceInsuredDTO.getAcceptDTOS();
        if (insuranceInsuredDTO == null || acceptDTOS == null || acceptDTOS.size() == 0){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4026);
        }
        //参保记录
        List<SeriesOrderInsuranceJoin> joinList = new ArrayList<>();
        for (AcceptDTO acceptDTO : acceptDTOS){
            SeriesOrderInsuranceJoin join = EntityUtil.copy(acceptDTO, SeriesOrderInsuranceJoin.class);
            join.setId(SnowflakeIdWorker.nextId());
            join.setInsuranceId(req.getInsuranceId());
            join.setOrderId(req.getOrderId());
            join.setScheduleId(order.getScheduleId());
            join.setCreateId(req.getUserId());
            join.setGmtCreate(LocalDateTime.now());
            join.setIsDeleted(0);
            joinList.add(join);
        }
        if(joinList.size() > 0){
            Integer batchJoin = orderInsuranceJoinMapper.insertBatchSomeColumn(joinList);
            if (batchJoin < joinList.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //更新保单状态
        insurance.setReceiptId(receipt.getId());
        insurance.setIsPay(1);
        insurance.setModifiedId(req.getUserId());
        int updateInsurance = orderInsuranceMapper.updateById(insurance);
        if (updateInsurance <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        SeriesOrderReceiptInsurance receiptInsurance = orderReceiptInsuranceMapper.selectById(insuranceReceiptId);
        receiptInsurance.setStampDutyPic(insuranceInsuredDTO.getStampDutyPic());
        receiptInsurance.setStampDutyAmount(insuranceInsuredDTO.getStampDutyAmount());
        receiptInsurance.setInsuranceNumber(insuranceInsuredDTO.getInsuranceReceiptNumber());
        //更新保单收据
        int updateById = orderReceiptInsuranceMapper.updateById(receiptInsurance);
        if (updateById <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //对接财务认款
        Result result = iFinanceBillService.addCollection(addListReq);
        if (result == null || !result.isSuccess()){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(receipt.getId());
    }



    /**
     * 封装参保请求参数
     * @param insurance 保单
     * @return
     */
    public List<AcceptUnderReq> packJoinInsuranceReq(SeriesOrderInsurance insurance) {
        List<AcceptUnderReq> list = new ArrayList<>();
        AcceptUnderReq acceptReq = new AcceptUnderReq();
        //投保人
        SeriesOrderTouristInfo applyer = orderTouristInfoMapper.selectById(insurance.getPolicyHolderId());
        if (applyer != null) {
            //投保人資訊
            ApplicantInfo appliGuRelatedPartyDto = new ApplicantInfo();
            appliGuRelatedPartyDto.setAge(applyer.getBirthday().until(LocalDate.now()).getYears() + "");
            appliGuRelatedPartyDto.setBirthDate(DateUtil.fmtLocalDate(applyer.getBirthday(), "yyyy-MM-dd"));
            appliGuRelatedPartyDto.setEmail(applyer.getEmail());
            appliGuRelatedPartyDto.setIdentifyNumber(applyer.getCertificateNumber1());
            appliGuRelatedPartyDto.setInsuredName(insurance.getPolicyHolderName());
            appliGuRelatedPartyDto.setInsuredEName(insurance.getPolicyHolderName());
            //证件类型 + 联系地址
            //    String identifyType = PacificUtil.getIdentifyType(applyer.getCertificateTypeId());
            appliGuRelatedPartyDto.setIdentifyType("03");
            appliGuRelatedPartyDto.setSex(applyer.getGender().toString());
            appliGuRelatedPartyDto.setMobilePhone(applyer.getMobile());
            acceptReq.setAppliGuRelatedPartyDto(appliGuRelatedPartyDto);
        }
        //被保人資訊列表
        List<InsuredInfo> guItemAcciListDtoList = new ArrayList<>();
        //旅客参保信息
        QueryWrapper<SeriesOrderInsurancePriceTourist> touristWrapper = new QueryWrapper<>();
        touristWrapper.eq("insurance_id", insurance.getId());
        touristWrapper.eq("order_id", insurance.getOrderId());
        List<SeriesOrderInsurancePriceTourist> touristList = orderInsurancePriceTouristMapper.selectList(touristWrapper);
        if (touristList != null && touristList.size() > 0) {
            //被保人資訊列表
            for (SeriesOrderInsurancePriceTourist tourist : touristList) {
                InsuredInfo guItemAcciListDto = new InsuredInfo();
                guItemAcciListDto.setAge(tourist.getAge().toString());
                guItemAcciListDto.setBirthday(DateUtil.fmtLocalDate(tourist.getBirthday(), "yyyy-MM-dd"));
                guItemAcciListDto.setSex(tourist.getSex().toString());
                guItemAcciListDto.setClientCName(tourist.getEnSurname() + tourist.getEnName());
                guItemAcciListDto.setIdentifyNoA(tourist.getCertificateNumber());
                //证件类型
                //    String identifyTypeA = PacificUtil.getIdentifyType(tourist.getCertificateTypeId());
                guItemAcciListDto.setIdentifyTypeA("03");
                //年龄类型
                //    String remark3 = PacificUtil.getAgeType(tourist.getAge());
                guItemAcciListDto.setRemark3("28");
                guItemAcciListDtoList.add(guItemAcciListDto);
            }
        }
        acceptReq.setGuItemAcciListDtoList(guItemAcciListDtoList);
        //險別咨訊
        acceptReq.setStartDate(DateUtil.fmtLocalDate(insurance.getBeginDate(), "yyyy-MM-dd"));
        acceptReq.setEndDate(DateUtil.fmtLocalDate(insurance.getEndDate(), "yyyy-MM-dd"));
        acceptReq.setStartPlace(insurance.getDeparturePlace());
        acceptReq.setEndPlace(insurance.getDestination());
        list.add(acceptReq);
        return list;
    }

    /**
     * 获取收据单号
     * @param userId
     * @return
     */
    public String getReceiptNumber(Long userId){
        String receiptNumber = null;
        try {
            UserDTO userDTO = iSysUserService.queryCacheUser(userId);
            if (userDTO != null){
                //收据单号 門市編號+員工編號+年後2位+月日4位+A+時分秒6位+（S）
                receiptNumber = userDTO.getDeptCode()+"-"+userDTO.getEmployeeNumber()+"-"+
                        DateUtil.fmt(LocalDateTime.now(),"yyMMddHHmmss")+"(S)";
            }
        }catch (Exception e){
            throw new BusinessException(SystemError.SYS_417);
        }
        return receiptNumber;
    }

    /**
     * 生成保险单号
     * @param userId
     * @return
     */
    public String getInsuranceNumber(Long userId){
        //保险单号 I+部門代碼+員工編號+年後2位+月日4位+3位隨機數字
        String insuranceNumber = null;
        try {
            UserDTO userDTO = iSysUserService.queryCacheUser(userId);
            if (userDTO != null){
                SysDepartmentDTO departmentDTO = iSysDepartmentService.queryOne(userDTO.getDeptId());
                if (departmentDTO != null){
                    insuranceNumber = "I-"+departmentDTO.getDeptCode()+"-"+userDTO.getEmployeeNumber()+"-"+
                            DateUtil.fmtLocalDate(LocalDate.now(),"yyMMdd")+"-"+ CharUtil.getRandomStr(3);
                }
            }
        }catch (Exception e){
            throw new BusinessException(SystemError.SYS_417);
        }
        return insuranceNumber;
    }

    /**
     * 保险报价
     * @param beginDate
     * @param endDate
     * @param rationType
     * @param apiCode
     * @param childNum
     * @param adultNum
     * @return
     */
    public OfferDTO insuranceOffer(LocalDate beginDate, LocalDate endDate, Integer rationType, String apiCode, Integer childNum, Integer adultNum,Long insuranceId) {
        //请求参数
        OfferReq offerReq = new OfferReq();
        Offer offer = new Offer();
        offer.setStarDate(DateUtil.fmtLocalDate(beginDate,"yyyy-MM-dd"));
        offer.setEndDate(DateUtil.fmtLocalDate(endDate,"yyyy-MM-dd"));
        offer.setRationType(Integer.valueOf(rationType));
        offer.setRiskCode(apiCode);
        offer.setChildCount((long)childNum);
        offer.setPersonCount((long)adultNum);
        offer.setInsuranceId(insuranceId);
        offerReq.setData(offer);
        OfferDTO offerDTOS = null;
        try {
            offerDTOS = iInsuranceService.acciQuotation(offerReq);
        }catch (Exception e){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4026);
        }
        if (offerDTOS == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4026);
        }
        return offerDTOS;
    }

    /**
     * 计算保险
     */
    @Override
    public Result calculationInsurance(SeriesOrderCollectionCalculationInsuranceReq req, TokenUser currentUser) {
        SeriesTripScheduleDTO tripScheduleDTO = iSeriesTripScheduleService.getTripScheduleId(req.getScheduleId());
        if (tripScheduleDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        SeriesTripScheduleDataDTO seriesTripScheduleDataDTO = tripScheduleDTO.getSeriesTripScheduleDataDTO();
        if (seriesTripScheduleDataDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        TripBasicInformationDTO tripBasicInformationDTO = iSeriesTripService.basicInformation(seriesTripScheduleDataDTO.getTripId());
        if (tripBasicInformationDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        SeriesTripReq seriesTripReq = tripBasicInformationDTO.getSeriesTripReq();
        if (seriesTripReq == null) {
            return Result.failed(SeriesOrderErrorCode.TRIP_NOT_INSURANCE_ERROR);
        }

        //计算人数
        List<SeriesOrderTouristInfo> touristInfoList = seriesOrderTouristInfoMapper.selectBatchIds(req.getTouristIdList());
        if (touristInfoList == null) {
            throw new BusinessException(SystemError.SYS_411);
        }
        if (touristInfoList.size() != req.getTouristIdList().size()) {
            throw new BusinessException(SystemError.SYS_411);
        }

        long personCount = 0;
        long childCount = 0;
        for (SeriesOrderTouristInfo touristInfo : touristInfoList) {
            //保险只能购买一次
            if (Objects.equals(touristInfo.getBuyInsurance(), ISCode.YES.getCode())) {
                continue;
            }

            int age = touristInfo.getBirthday().until(LocalDate.now()).getYears();
            if (age >= 18) {
                personCount++;
            } else {
                childCount++;
            }
        }

        if (personCount == 0 && childCount == 0) {
            return Result.failed(SeriesOrderErrorCode.BUY_ALL_INSURANCE_ERROR);
        }

        List<InsuranceProductDTO> records = new ArrayList<>();
        List<Long> insuranceIdList = new ArrayList<>();
        for (TripInsuranceReq tripInsuranceReq : seriesTripReq.getInsuranceList()) {
            insuranceIdList.add(tripInsuranceReq.getInsuranceId());
        }
        InsuranceProductReq insuranceProductReq = new InsuranceProductReq();
        insuranceProductReq.setIds(insuranceIdList);
        PageResponse<InsuranceProductDTO> insuranceProductDTOPageResponse = iInsuranceService.queryList(insuranceProductReq);
        if (insuranceProductDTOPageResponse != null && insuranceProductDTOPageResponse.getRecords() != null) {
            records = insuranceProductDTOPageResponse.getRecords();
        }

        SeriesOrderCollectionCalculationInsuranceDTO model = EntityUtil.copy(req, SeriesOrderCollectionCalculationInsuranceDTO.class);
        List<SeriesOrderCollectionCalculationInsuranceNameDTO> itemList = new ArrayList<>();
        for (InsuranceProductDTO insuranceProductDTO : records) {

            SeriesOrderCollectionCalculationInsuranceNameItemDTO nameItemDTO1 = new SeriesOrderCollectionCalculationInsuranceNameItemDTO();
            nameItemDTO1.setTouristTypeName("成人");
            nameItemDTO1.setTouristTypeNum(personCount);
            SeriesOrderCollectionCalculationInsuranceNameItemDTO nameItemDTO2 = new SeriesOrderCollectionCalculationInsuranceNameItemDTO();
            nameItemDTO2.setTouristTypeName("小童");
            nameItemDTO2.setTouristTypeNum(childCount);

            ArrayList<SeriesOrderCollectionCalculationInsuranceNameItemDTO> nameItemList = new ArrayList<>();
            nameItemList.add(nameItemDTO1);
            nameItemList.add(nameItemDTO2);

            SeriesOrderCollectionCalculationInsuranceNameDTO insuranceNameItemDTO = EntityUtil.copy(insuranceProductDTO,
                    SeriesOrderCollectionCalculationInsuranceNameDTO.class);
            insuranceNameItemDTO.setItemList(nameItemList);

            itemList.add(insuranceNameItemDTO);
        }
        model.setItemList(itemList);

        if (req.getStartDate() == null) {
            req.setStartDate(tripScheduleDTO.getDepartureDate());
        }
        if (req.getEndDate() == null) {
            req.setEndDate(tripScheduleDTO.getBackDate());
        }

        //报价
        BigDecimal totalAmount = new BigDecimal(0);
        if (req.getInsuranceId() != null) {
            InsuranceDTO detail = iInsuranceService.detail(req.getInsuranceId());
            OfferReq offerReq = new OfferReq();
            Offer offer = new Offer();
            offer.setPersonCount(personCount);
            offer.setChildCount(childCount);
            offer.setRationType(Integer.valueOf(detail.getRationType()));
            offer.setRiskCode(detail.getApiCode());
            offer.setStarDate(Utils.getDateString(req.getStartDate(), Utils.yyyy_MM_dd));
            offer.setEndDate(Utils.getDateString(req.getEndDate(), Utils.yyyy_MM_dd));
            offerReq.setData(offer);
            try {
                OfferDTO offerDTO = iInsuranceService.acciQuotation(offerReq);
                if (offerDTO == null) {
                    throw new BusinessException();
                }
                totalAmount = totalAmount.add(offerDTO.getPremium());
            } catch (Exception e) {
                throw new BusinessException(SystemError.SYS_500);
            }
        }
        model.setTotalAmount(totalAmount);
        return Result.success(model);
    }


    /**
     * 验证优惠
     */
    @Override
    public Result verifyDiscount(SeriesOrderCollectionVerifyDiscountReq req) {
        BigDecimal totalAmount = new BigDecimal(0);

        Map<Long, BigDecimal> map = new HashMap<>();
        for (Long touristId : req.getTouristIdList()) {
            QueryWrapper<SeriesOrderTouristInfo> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getOrderId, req.getOrderId());
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getId, touristId);
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getIsDeleted, IsDeletedCode.NO.getCode());
            SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectOne(queryWrapper2);
            if (touristInfo == null) {
                return Result.failed(SystemError.SYS_411);
            }

            QueryWrapper<SeriesOrderTouristFeeAdjust> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getTouristId, touristId);
            queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getAdjustType, AdjustTypeCode.ADJUST.getCode());
            queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getIsDeleted, IsDeletedCode.NO.getCode());
            List<SeriesOrderTouristFeeAdjust> feeAdjustList = seriesOrderTouristFeeAdjustMapper.selectList(queryWrapper);
            BigDecimal touristAmount = touristInfo.getGroupFee();
            for (SeriesOrderTouristFeeAdjust feeAdjust : feeAdjustList) {
                if (Objects.equals(feeAdjust.getPlusType(), PlusTypeCode.PLUS.getCode())) {
                    touristAmount = touristAmount.add(feeAdjust.getAmount());
                } else if (Objects.equals(feeAdjust.getPlusType(), PlusTypeCode.SUBTRACT.getCode())) {
                    touristAmount = touristAmount.subtract(feeAdjust.getAmount());
                }
            }
            totalAmount = totalAmount.add(touristAmount);
            map.put(touristId, touristAmount);
        }

        OperatePromotionConformReq operatePromotionConformReq = new OperatePromotionConformReq();
        operatePromotionConformReq.setActivityCode(req.getActivityCode());
        operatePromotionConformReq.setBusinessType(SystemBusinessType.OUTBOUND_TRAVEL.getCode());
        operatePromotionConformReq.setRelationId(req.getScheduleId());
        operatePromotionConformReq.setUserId(req.getUserId());
        operatePromotionConformReq.setTotalPaidIn(totalAmount);
        operatePromotionConformReq.setChannelId(OrderSource.CPM.getCode().longValue());
        SeriesOrder dbOrder = seriesOrderMapper.selectById(req.getOrderId());
        if (dbOrder == null || Objects.equals(dbOrder.getIsDeleted(),1)) {
            return Result.failed(SystemError.SYS_411);
        }
        //会员类型（1:星赏会会员,2:普通会员,3:无会员）
        Integer type = 3;
        //会员手机号为空
        if (dbOrder.getMemberMobile() != null){
            CrmMemberQueryReq crmMemberQueryReq = new CrmMemberQueryReq(QueryType.PHONE.getCode(), dbOrder.getMemberMobile(), null);
            CrmAccountDTO crmAccountDTO = iCrmMemberService.queryAccountDetail(crmMemberQueryReq);
            if (crmAccountDTO != null) {
                type = crmAccountDTO.getType();
            }
        }

        operatePromotionConformReq.setDiscountObjectId(type.longValue());
        Result<OperatePromotionQueryDTO> promotionQueryDTOResult = iOperatePromotionService.queryConform(operatePromotionConformReq);

        int isEffective = ISCode.NO.getCode();
        int effectiveNum = 0;
        BigDecimal reductionAmount = new BigDecimal(0);
        SeriesOrderVerifyPromotionDTO dto = new SeriesOrderVerifyPromotionDTO();
        if (promotionQueryDTOResult.isSuccess() &&
                promotionQueryDTOResult.getData() != null) {
            OperatePromotionQueryDTO promotionQueryDTO = promotionQueryDTOResult.getData();
            dto.setDiscountId(promotionQueryDTO.getId());

            for (Long touristId : req.getTouristIdList()) {
                //對於已使用優惠的旅客不能再繼續使用
                QueryWrapper<SeriesOrderCollection> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.lambda().eq(SeriesOrderCollection::getOrderId, req.getOrderId());
                queryWrapper2.lambda().eq(SeriesOrderCollection::getTouristId, touristId);
                queryWrapper2.lambda().eq(SeriesOrderCollection::getCollectionWayId, CollectionRefundWayIdCode.OPERATE_PROMOTION.getCode());
                queryWrapper2.lambda().eq(SeriesOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode());
                Integer count = seriesOrderCollectionMapper.selectCount(queryWrapper2);
                if (count > 0) {
                    continue;
                }

                BigDecimal touristAmount = map.get(touristId);
                if (touristAmount.compareTo(promotionQueryDTO.getFullAmount()) >= 0) {
                    isEffective = ISCode.YES.getCode();
                    effectiveNum++;
                }
            }
            reductionAmount = promotionQueryDTO.getReductionAmount();
        }
        dto.setReductionAmount(reductionAmount);
        dto.setIsEffective(isEffective);
        dto.setEffectiveNum(effectiveNum);
        return Result.success(dto);
    }

    /**
     * 使用优惠（推广码：内部挂账）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result useDiscount(SeriesOrderCollectionUseDiscountReq req, TokenUser currentUser) {
        SeriesOrder order = seriesOrderMapper.selectById(req.getOrderId());
        if (order == null) {
            return Result.failed(SystemError.SYS_411);
        }
        if (Objects.equals(order.getOrderType(), OrderTypeCode.PROXY.getCode())) {
            return Result.failed(SeriesOrderErrorCode.POINTS_USE_PROXY_LIMIT);
        }
        //团期详情
        SeriesTripScheduleDTO tripSchedule = iSeriesTripScheduleService.getTripScheduleId(req.getScheduleId());
        //查询推广码详情
        OperatePromotionQueryReq operatePromotionQueryReq = new OperatePromotionQueryReq();
        operatePromotionQueryReq.setId(req.getDiscountId());
        Result<OperatePromotionQueryDTO> operatePromotionQueryDTOResult = iOperatePromotionService.query(operatePromotionQueryReq);
        if (!operatePromotionQueryDTOResult.isSuccess() || operatePromotionQueryDTOResult.getData() == null) {
            return Result.failed(SystemError.SYS_411);
        }
        OperatePromotionQueryDTO promotionQueryDTO = operatePromotionQueryDTOResult.getData();
        //查询收款类型主数据
        MainDataFieldDataDTO collectionTypeDTO = iMainDataFieldDataService.queryFieldData(CollectionTypeIdCode.OTHER.getCode());
        if (collectionTypeDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        //查询币种
        MainDataCurrencyUpdateStatusReq currencyUpdateStatusReq = new MainDataCurrencyUpdateStatusReq();
        currencyUpdateStatusReq.setId(CurrencyIdCode.HKD.getCode());
        Result<MainDataCurrencyQueryDTO> currencyQueryDTOResult = iMainDataCurrencyService.query(currencyUpdateStatusReq);
        if (!currencyQueryDTOResult.isSuccess() || currencyQueryDTOResult.getData() == null) {
            return Result.failed(SystemError.SYS_411);
        }
        MainDataCurrencyQueryDTO currencyQueryDTO = currencyQueryDTOResult.getData();

        MainDataPaymentRefundTypeIdReq operatePromotionReq = new MainDataPaymentRefundTypeIdReq();
        operatePromotionReq.setId(CollectionRefundWayIdCode.OPERATE_PROMOTION.getCode());
        MainDataPaymentRefundTypeDTO operatePromotionDTO = iMainDataPaymentRefundTypeService.query(operatePromotionReq);
        if (operatePromotionDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }
        //会员类型（1:星赏会会员,2:普通会员,3:无会员）
        Integer type = 3;
        if (order.getMemberMobile() != null){
            CrmMemberQueryReq crmMemberQueryReq = new CrmMemberQueryReq(QueryType.PHONE.getCode(), order.getMemberMobile(), null);
            CrmAccountDTO crmAccountDTO = iCrmMemberService.queryAccountDetail(crmMemberQueryReq);
            if (crmAccountDTO != null) {
                type = crmAccountDTO.getType();
            }
        }

        List<SeriesOrderCollection> collectionList = new ArrayList<>();
        List<BillAddCollectionReq> addListReq = new ArrayList<>();
        List<UseQuotaReq> useQuotaReqList = new ArrayList<>();

        for (Long touristId : req.getTouristIdList()) {
            QueryWrapper<SeriesOrderCollection> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.lambda().eq(SeriesOrderCollection::getOrderId, req.getOrderId());
            queryWrapper4.lambda().eq(SeriesOrderCollection::getTouristId, touristId);
            queryWrapper4.lambda().eq(SeriesOrderCollection::getCollectionWayId, CollectionRefundWayIdCode.OPERATE_PROMOTION.getCode());
            queryWrapper4.lambda().eq(SeriesOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode());
            Integer discountCount = seriesOrderCollectionMapper.selectCount(queryWrapper4);
            if (discountCount > 0) {
                continue;
            }

            QueryWrapper<SeriesOrderTouristInfo> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getOrderId, req.getOrderId());
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getId, touristId);
            queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getIsDeleted, IsDeletedCode.NO.getCode());
            SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectOne(queryWrapper2);
            if (touristInfo == null) {
                throw new BusinessException(SystemError.SYS_411);
            }

            QueryWrapper<SeriesOrderTouristFeeAdjust> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getTouristId, touristId);
            queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getAdjustType, AdjustTypeCode.ADJUST.getCode());
            queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getIsDeleted, IsDeletedCode.NO.getCode());
            List<SeriesOrderTouristFeeAdjust> feeAdjustList = seriesOrderTouristFeeAdjustMapper.selectList(queryWrapper);
            BigDecimal touristAmount = touristInfo.getGroupFee();
            for (SeriesOrderTouristFeeAdjust feeAdjust : feeAdjustList) {
                if (Objects.equals(feeAdjust.getPlusType(), PlusTypeCode.PLUS.getCode())) {
                    touristAmount = touristAmount.add(feeAdjust.getAmount());
                } else if (Objects.equals(feeAdjust.getPlusType(), PlusTypeCode.SUBTRACT.getCode())) {
                    touristAmount = touristAmount.subtract(feeAdjust.getAmount());
                }
            }
            if (touristAmount.compareTo(promotionQueryDTO.getFullAmount()) >= 0) {
                BigDecimal discountAmount = touristAmount.subtract(promotionQueryDTO.getReductionAmount());
                BigDecimal discountHkdAmount = iMainDataCurrencyService.getHkdAmount(collectionTypeDTO.getId(),discountAmount);
                SeriesOrderCollection collection = new SeriesOrderCollection();
                LocalDateTime now = LocalDateTime.now();
                collection.setId(SnowflakeIdWorker.nextId());
                collection.setGmtCreate(now);
                collection.setIsDeleted(IsDeletedCode.NO.getCode());
                collection.setGmtModified(now);
                collection.setCreateId(req.getUserId());
                collection.setModifiedId(req.getUserId());
                collection.setIsPos(IsPosCode.NOT_USE.getCode());
                collection.setCollectionNumber(iSeriesOrderService.getCollectionNumber());
                collection.setStatus(SeriesOrderCollectionStatusCode.APPROVAL.getCode());
                collection.setOrderId(req.getOrderId());
                collection.setScheduleId(req.getScheduleId());
                collection.setIsPrint(ISCode.NO.getCode());
                collection.setPaidInAmount(discountHkdAmount);
                collection.setCurrencyPaidInAmount(discountAmount);
                collection.setCurrencyType(currencyQueryDTO.getCurrencyName());
                collection.setCurrencyTypeId(CurrencyIdCode.HKD.getCode());
                collection.setExchangeRate(currencyQueryDTO.getMarketExchangeRate());
                collection.setCollectionTypeId(collectionTypeDTO.getId());
                collection.setCollectionType(collectionTypeDTO.getFieldValue());
                collection.setCollectionWayId(operatePromotionDTO.getId());
                collection.setCollectionWay(operatePromotionDTO.getPaymentRefundName());
                RelationInfoJsonDiscount relationInfoJson = new RelationInfoJsonDiscount();
                relationInfoJson.setDiscountId(req.getDiscountId());
                relationInfoJson.setDiscountType(RelationInfoJsonDiscountTypeCode.PROMOTION.getCode());
                collection.setRelationInfoJson(JSON.toJSONString(relationInfoJson));
                collectionList.add(collection);

                //财务认款请求参数
                BillAddCollectionReq addReq = new BillAddCollectionReq();
                addReq.setBillNumber(collection.getCollectionNumber());
                addReq.setBusinessType(SystemBusinessType.OUTBOUND_TRAVEL.getCode());
                addReq.setCollectionWayId(collection.getCollectionWayId());
                addReq.setCollectionWayName(collection.getCollectionWay());
                addReq.setCollectionTypeId(collection.getCollectionTypeId());
                addReq.setCollectionTypeName(collection.getCollectionType());
                addReq.setCollectionAmount(collection.getPaidInAmount());
                addReq.setCurrencyId(collection.getCurrencyTypeId());
                addReq.setCurrencyName(collection.getCurrencyType());
                addReq.setExchangeRate(collection.getExchangeRate().doubleValue());
                addReq.setCollectionTime(collection.getGmtCreate());
            //    addReq.setCollectionVoucherJsonList(item.getCollectionVoucherJsonList());
                addReq.setSaleOrderNumber(order.getOrderNumber());
                addReq.setSaleOrderId(order.getId());
                addReq.setProductNumber(tripSchedule.getTripNumber());
                addReq.setProductName(tripSchedule.getSeriesTripScheduleDataDTO().getTitle());
                List<String> resourceInfo = new ArrayList<>();
                resourceInfo.add(tripSchedule.getSeriesTripScheduleDataDTO().getTitle());
                addReq.setResourceInfo(resourceInfo);
                addReq.setSaleUserId(collection.getCreateId());
                UserDTO userDTO = iSysUserService.queryCacheUser(collection.getCreateId());
                addReq.setSaleUserName(userDTO.getFullName());
                addReq.setSaleDeptId(userDTO.getDeptId());
                addReq.setUserId(currentUser.getId());
                addListReq.add(addReq);

                //财务挂账
                UseQuotaReq req1 = new UseQuotaReq();
                req1.setUserId(currentUser.getId());
                req1.setAccountType(2);
                req1.setDeptId(promotionQueryDTO.getDepartmentId());
                req1.setAmount(collection.getCurrencyPaidInAmount());
                req1.setBigClientName(promotionQueryDTO.getDepartmentName());
                req1.setCollectionTypeId(collection.getCollectionTypeId());
                req1.setCollectionTypeName(collection.getCollectionType());
                req1.setCollectionWayId(collection.getCollectionWayId());
                req1.setCollectionWayName(collection.getCollectionWay());
                req1.setBillNumber(collection.getCollectionNumber());
                req1.setBusinessType(SystemBusinessType.OUTBOUND_TRAVEL.getCode());
                req1.setCollectionTime(collection.getGmtCreate());
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(collection.getCollectionVoucherJson())){
                    List<FileJson> fileJsons = JSON.parseArray(collection.getCollectionVoucherJson(), FileJson.class);
                    req1.setCollectionVoucherJson(fileJsons);
                }
                req1.setCurrencyId(collection.getCurrencyTypeId());
                req1.setCurrencyName(collection.getCurrencyType());
                req1.setExchangeRate(collection.getExchangeRate().doubleValue());
                req1.setContactMobile(touristInfo.getMobile());
                req1.setTouristName(touristInfo.getCnFullname()==null?touristInfo.getEnFullname():touristInfo.getCnFullname());
                req1.setTouristSource(order.getCustomerType());
                req1.setSaleOrderId(order.getId());
                req1.setSaleOrderNumber(order.getOrderNumber());
                req1.setProductId(order.getScheduleId());
                if (tripSchedule != null){
                    req1.setProductName(tripSchedule.getSeriesTripScheduleDataDTO().getTitle());
                    req1.setTripNumber(tripSchedule.getTripNumber());
                    List<String> resourceInfo1 = new ArrayList<>();
                    resourceInfo1.add(tripSchedule.getSeriesTripScheduleDataDTO().getTitle());
                    req1.setResourceInfo(resourceInfo1);
                }
                req1.setSaleUserId(order.getId());
                if (userDTO != null){
                    req1.setSaleUserName(userDTO.getFullName());
                }
                useQuotaReqList.add(req1);

                //游客统计
                touristInfo.setTotalPaidIn(touristInfo.getTotalPaidIn().add(collection.getPaidInAmount()));
                touristInfo.setRemainingReceivables(touristInfo.getRemainingReceivables().subtract(collection.getPaidInAmount()));

                if (touristInfo.getTotalPaidIn().compareTo(touristInfo.getTotalReceivables()) == 0) {
                    touristInfo.setPayStatus(PayStatusCode.FULL_PAYED.getCode());
                } else if (touristInfo.getTotalPaidIn().compareTo(new BigDecimal(0)) > 0 &&
                        touristInfo.getTotalPaidIn().compareTo(touristInfo.getTotalReceivables()) < 0) {
                    touristInfo.setPayStatus(PayStatusCode.WAIT_REMAIN.getCode());
                }
                int updateInfo = seriesOrderTouristInfoMapper.updateById(touristInfo);

                //订单统计
                QueryWrapper<SeriesOrderAmountStatistics> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.lambda().eq(SeriesOrderAmountStatistics::getOrderId, collection.getOrderId());
                SeriesOrderAmountStatistics statistics = seriesOrderAmountStatisticsMapper.selectOne(queryWrapper3);
                statistics.setTotalPaidIn(statistics.getTotalPaidIn().add(collection.getPaidInAmount()));
                statistics.setRemainingReceivables(statistics.getRemainingReceivables().subtract(collection.getPaidInAmount()));
                int updateStatistics = seriesOrderAmountStatisticsMapper.updateById(statistics);
                if (updateInfo <= 0 || updateStatistics <= 0){
                    throw new BusinessException(SystemError.SYS_408);
                }

                //推廣碼的使用後，n個旅客使用後會生成n條記錄

                //优惠金额
                OperatePromotionDeductReq operatePromotionDeductReq = new OperatePromotionDeductReq();
                operatePromotionDeductReq.setId(req.getDiscountId());
                operatePromotionDeductReq.setBusinessType(SystemBusinessType.OUTBOUND_TRAVEL.getCode());
                operatePromotionDeductReq.setTotalPaidIn(discountAmount);
                operatePromotionDeductReq.setRelationId(req.getScheduleId());
                operatePromotionDeductReq.setProductNumber(order.getScheduleNumber());
                operatePromotionDeductReq.setProductName(order.getTripTitle());
                operatePromotionDeductReq.setChannelId(OrderSource.CPM.getCode().longValue());
                operatePromotionDeductReq.setDiscountObjectId(type.longValue());
                Result result = iOperatePromotionService.deduct(operatePromotionDeductReq, currentUser);
                if (!result.isSuccess()) {
                    throw new BusinessException(SeriesOrderErrorCode.DISCOUNT_NOT_USE_ERROR);
                }
            }
        }
        if (collectionList.size() > 0){
            boolean saveBatch = saveBatch(collectionList);
            if (!saveBatch){
                throw new BusinessException(SystemError.SYS_408);
            }
        }
        //更新会员信息
        /*dbOrder.setMemberId(crmAccountDTO.getConIntegrationId());
        dbOrder.setMemberEmail(crmAccountDTO.getConEmailAddr());
        dbOrder.setMemberMobile(crmAccountDTO.getConCellPhNum());
        dbOrder.setMemberLevel(String.valueOf(crmAccountDTO.getLevel()));
        dbOrder.setMemberName(crmAccountDTO.getNameCn());
        dbOrder.setMemberType(crmAccountDTO.getType());
        if(Objects.equals(crmAccountDTO.getType(), CrmAccountType.STAR.getCode())) {
            ContactQueryDTO contactQueryDTO = iCrmMemberService.queryMember(crmMemberQueryReq);
            if(contactQueryDTO == null) {
                throw new BusinessException(SystemError.SYS_411);
            }
            dbOrder.setMemberScore(String.valueOf(contactQueryDTO.getMember().getPoint1Value()));
        }
        seriesOrderMapper.updateById(dbOrder);*/
        //对接财务认款
        if (addListReq.size() > 0){
            Result result = iFinanceBillService.addCollection(addListReq);
            if (result == null || !result.isSuccess()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //新增财务挂账使用记录
        if (useQuotaReqList.size() > 0){
            Result result1 = financeOnAccountCurrencyQuotaService.useQuota(useQuotaReqList);
            if (result1 == null || !result1.isSuccess()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        return Result.success();
    }

    /**
     * 使用积分
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result usePoints(SeriesOrderCollectionUsePointsReq req, TokenUser currentUser) {
        if (req.getPoints() == null) {
            return Result.failed(SystemError.SYS_409);
        }

        SeriesOrder dbOrder = seriesOrderMapper.selectById(req.getOrderId());
        if (StringUtils.isBlank(dbOrder.getMemberMobile())) {
            return Result.failed(SeriesOrderErrorCode.MEMBER_NOT_FOUND_ERROR);
        }

        QueryWrapper<SeriesOrderCollection> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.lambda().eq(SeriesOrderCollection::getOrderId, req.getOrderId());
        queryWrapper4.lambda().eq(SeriesOrderCollection::getTouristId, req.getTouristId());
        queryWrapper4.lambda().eq(SeriesOrderCollection::getCollectionWayId, CollectionRefundWayIdCode.POINTS.getCode());
        queryWrapper4.lambda().eq(SeriesOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode());
        Integer collectionCount = seriesOrderCollectionMapper.selectCount(queryWrapper4);
        if (collectionCount > 0) {
            return Result.failed(SeriesOrderErrorCode.POINTS_USE_LIMIT);
        }

        MainDataFieldDataDTO collectionTypeDTO = iMainDataFieldDataService.queryFieldData(
                CollectionTypeIdCode.FULL.getCode());
        if (collectionTypeDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }

        MainDataCurrencyUpdateStatusReq cnyCurrencyUpdateStatusReq = new MainDataCurrencyUpdateStatusReq();
        cnyCurrencyUpdateStatusReq.setId(CurrencyIdCode.CNY.getCode());
        Result<MainDataCurrencyQueryDTO> cnyCurrencyQueryDTOResult = iMainDataCurrencyService.query(cnyCurrencyUpdateStatusReq);
        if (!cnyCurrencyQueryDTOResult.isSuccess() || cnyCurrencyQueryDTOResult.getData() == null) {
            return Result.failed(SystemError.SYS_411);
        }
        MainDataCurrencyQueryDTO cnyCurrencyQueryDTO = cnyCurrencyQueryDTOResult.getData();

        MainDataCurrencyUpdateStatusReq hkdCurrencyUpdateStatusReq = new MainDataCurrencyUpdateStatusReq();
        hkdCurrencyUpdateStatusReq.setId(CurrencyIdCode.HKD.getCode());
        Result<MainDataCurrencyQueryDTO> hkdCurrencyQueryDTOResult = iMainDataCurrencyService.query(hkdCurrencyUpdateStatusReq);
        if (!hkdCurrencyQueryDTOResult.isSuccess() || hkdCurrencyQueryDTOResult.getData() == null) {
            return Result.failed(SystemError.SYS_411);
        }
        MainDataCurrencyQueryDTO hkdCurrencyQueryDTO = hkdCurrencyQueryDTOResult.getData();

        MainDataPaymentRefundTypeIdReq pointsReq = new MainDataPaymentRefundTypeIdReq();
        pointsReq.setId(CollectionRefundWayIdCode.POINTS.getCode());
        MainDataPaymentRefundTypeDTO pointsDTO = iMainDataPaymentRefundTypeService.query(pointsReq);
        if (pointsDTO == null) {
            return Result.failed(SystemError.SYS_411);
        }

        QueryWrapper<SeriesOrderTouristInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getOrderId, req.getOrderId());
        queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getId, req.getTouristId());
        queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getIsDeleted, IsDeletedCode.NO.getCode());
        SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectOne(queryWrapper2);
        if (touristInfo == null) {
            return Result.failed(SystemError.SYS_411);
        }

        //可抵扣金額（HKD）=團費+調整費用（不包括簽證、保險、更改旅客資料）
        QueryWrapper<SeriesOrderTouristFeeAdjust> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getTouristId, req.getTouristId());
        queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getAdjustType, AdjustTypeCode.ADJUST.getCode());
        queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getIsDeleted, IsDeletedCode.NO.getCode());
        List<SeriesOrderTouristFeeAdjust> feeAdjustList = seriesOrderTouristFeeAdjustMapper.selectList(queryWrapper);
        BigDecimal touristAmount = touristInfo.getGroupFee();
        for (SeriesOrderTouristFeeAdjust feeAdjust : feeAdjustList) {
            if (Objects.equals(feeAdjust.getPlusType(), PlusTypeCode.PLUS.getCode())) {
                touristAmount = touristAmount.add(feeAdjust.getAmount());
            } else if (Objects.equals(feeAdjust.getPlusType(), PlusTypeCode.SUBTRACT.getCode())) {
                touristAmount = touristAmount.subtract(feeAdjust.getAmount());
            }
        }

        if (dbOrder.getMemberId() == null || StringUtils.isBlank(dbOrder.getMemberMobile())) {
            throw new BusinessException(SeriesOrderErrorCode.USE_POINTS_LIMIT);
        }
        CrmMemberQueryReq crmMemberQueryReq = new CrmMemberQueryReq(QueryType.PHONE.getCode(), dbOrder.getMemberMobile(), null);
        CrmAccountDTO crmAccountDTO = iCrmMemberService.queryAccountDetail(crmMemberQueryReq);
        if (crmAccountDTO == null) {
            throw new BusinessException(SeriesOrderErrorCode.USE_POINTS_LIMIT);
        }
        ContactQueryDTO contactQueryDTO = null;
        if (Objects.equals(crmAccountDTO.getType(), CrmAccountType.STAR.getCode())) {
            contactQueryDTO = iCrmMemberService.queryMember(crmMemberQueryReq);
            if (contactQueryDTO == null) {
                throw new BusinessException(SeriesOrderErrorCode.USE_POINTS_LIMIT);
            }
        } else {
            throw new BusinessException(SeriesOrderErrorCode.USE_POINTS_LIMIT);
        }

        BigDecimal points = BigDecimal.valueOf(req.getPoints());
        MathContext context = new MathContext(2, RoundingMode.HALF_DOWN);

        //校验积分是否充足
        BigDecimal memberPoints = BigDecimal.valueOf(contactQueryDTO.getMember().getPoint1Value());
        if (points.compareTo(memberPoints) > 0) {
            // 会员积分不足
            throw new BusinessException(SystemError.AIREXPRESS_ORDER_60008);
        }

        //可用積分=可抵扣金額（HKD）÷人民幣CRM匯率×100
        BigDecimal availablePoints = (touristAmount.divide(cnyCurrencyQueryDTO.getCrmExchangeRate(), context)).multiply(
                new BigDecimal(100));

        //检查使用的积分不能大于可用积分
        if (points.compareTo(availablePoints) > 0) {
            throw new BusinessException(SeriesOrderErrorCode.MEMBER_USE_POINTS_LIMIT);
        }

        //本次抵扣：積分抵扣金額（HKD）= （積分數÷100)×人民幣CRM匯率
        BigDecimal deductionAmount = (points.divide(
                new BigDecimal(100), context)).multiply(
                cnyCurrencyQueryDTO.getCrmExchangeRate());

        SeriesOrderCollection collection = new SeriesOrderCollection();
        LocalDateTime now = LocalDateTime.now();
        collection.setId(IdWorker.getId());
        collection.setGmtCreate(now);
        collection.setIsDeleted(IsDeletedCode.NO.getCode());
        collection.setGmtModified(now);
        collection.setCreateId(req.getUserId());
        collection.setModifiedId(req.getUserId());
        collection.setIsPos(IsPosCode.NOT_USE.getCode());
        collection.setCollectionNumber(iSeriesOrderService.getCollectionNumber());
        collection.setStatus(SeriesOrderCollectionStatusCode.APPROVAL.getCode());
        collection.setOrderId(req.getOrderId());
        collection.setScheduleId(req.getScheduleId());
        collection.setIsPrint(ISCode.NO.getCode());
        collection.setPaidInAmount(deductionAmount);
        collection.setCurrencyPaidInAmount(deductionAmount);
        collection.setCurrencyType(hkdCurrencyQueryDTO.getCurrencyName());
        collection.setCurrencyTypeId(CurrencyIdCode.HKD.getCode());
        collection.setCollectionTypeId(collectionTypeDTO.getId());
        collection.setCollectionType(collectionTypeDTO.getFieldValue());
        collection.setCollectionWayId(pointsDTO.getId());
        collection.setCollectionWay(pointsDTO.getPaymentRefundName());

        seriesOrderCollectionMapper.insert(collection);

        //游客统计
        touristInfo.setTotalPaidIn(touristInfo.getTotalPaidIn().add(collection.getPaidInAmount()));
        touristInfo.setRemainingReceivables(touristInfo.getRemainingReceivables().subtract(collection.getPaidInAmount()));

        if (touristInfo.getTotalPaidIn().compareTo(touristInfo.getTotalReceivables()) == 0) {
            touristInfo.setPayStatus(PayStatusCode.FULL_PAYED.getCode());
        } else if (touristInfo.getTotalPaidIn().compareTo(new BigDecimal(0)) > 0 &&
                touristInfo.getTotalPaidIn().compareTo(touristInfo.getTotalReceivables()) < 0) {
            touristInfo.setPayStatus(PayStatusCode.WAIT_REMAIN.getCode());
        }
        seriesOrderTouristInfoMapper.updateById(touristInfo);

        //订单统计
        QueryWrapper<SeriesOrderAmountStatistics> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.lambda().eq(SeriesOrderAmountStatistics::getOrderId, collection.getOrderId());
        SeriesOrderAmountStatistics statistics = seriesOrderAmountStatisticsMapper.selectOne(queryWrapper3);
        statistics.setTotalPaidIn(statistics.getTotalPaidIn().add(collection.getPaidInAmount()));
        statistics.setRemainingReceivables(statistics.getRemainingReceivables().subtract(collection.getPaidInAmount()));
        seriesOrderAmountStatisticsMapper.updateById(statistics);

        BigDecimal xCtsRmbAmount = deductionAmount.divide(cnyCurrencyQueryDTO.getCrmExchangeRate(), 2, BigDecimal.ROUND_HALF_UP);
        CrmMemberUpdatePointsReq crmMemberUpdatePointsReq = new CrmMemberUpdatePointsReq();
        crmMemberUpdatePointsReq.setMemberId(dbOrder.getMemberMobile());
        crmMemberUpdatePointsReq.setUpdateType(PlusTypeCode.SUBTRACT.getCode());
        crmMemberUpdatePointsReq.setNumPoints(points);//do积分点数
        crmMemberUpdatePointsReq.setXCtsProdDesc(ProdNameCode.HK_MO_GROUP.getMsg() + "-" + XCtsProdCode.THEME_TOURIST.getMsg() + "(旅行團)");//do板塊產品描述 (建議使用: 集團產品名稱 + “ – “ + 板塊產品名稱, 例如: 港澳参团游 - 主题游)")
        crmMemberUpdatePointsReq.setTxnNum(dbOrder.getOrderNumber());//do交易編號 (如為旅行團交易, 目前我們的格式是 旅行團交易編號 + ‘-‘ + 序號, 例如: 01P08192131025A155506-1
        crmMemberUpdatePointsReq.setAmtVal(deductionAmount);
        crmMemberUpdatePointsReq.setXCtsRmbAmount(xCtsRmbAmount);
        crmMemberUpdatePointsReq.setCreateUserid(String.valueOf(currentUser.getId()).substring(0, 12));
        crmMemberUpdatePointsReq.setXCtsTxnOrgCode(XCtsTxnOrgCode.HK_MO_MARKET.getCode());
        crmMemberUpdatePointsReq.setTxnChannelCd(TxnChannelCdCode.STORE.getCode());
        if (Objects.equals(dbOrder.getOrderType(), OrderTypeCode.CLIENT.getCode())) {
            crmMemberUpdatePointsReq.setXCtsTxnChnNum(XCtsTxnChnNumCode.HK_TOURIST_MARKET.getCode());
        } else if (Objects.equals(dbOrder.getOrderType(), OrderTypeCode.PROXY.getCode())) {
            crmMemberUpdatePointsReq.setXCtsTxnChnNum(XCtsTxnChnNumCode.HK_TOURIST_PROXY.getCode());
        }
        crmMemberUpdatePointsReq.setProdName(ProdNameCode.HK_MO_GROUP.getCode());
        crmMemberUpdatePointsReq.setXCtsProdCode(XCtsProdCode.THEME_TOURIST.getCode());
        iCrmMemberService.updatePoints(crmMemberUpdatePointsReq, contactQueryDTO);

        //更新会员信息
        dbOrder.setMemberId(crmAccountDTO.getConIntegrationId());
        dbOrder.setMemberEmail(crmAccountDTO.getConEmailAddr());
        dbOrder.setMemberMobile(crmAccountDTO.getConCellPhNum());
        dbOrder.setMemberLevel(String.valueOf(crmAccountDTO.getLevel()));
        dbOrder.setMemberName(crmAccountDTO.getNameCn());
        dbOrder.setMemberType(crmAccountDTO.getType());

        if (Objects.equals(crmAccountDTO.getType(), CrmAccountType.STAR.getCode())) {
            contactQueryDTO = iCrmMemberService.queryMember(crmMemberQueryReq);
            if (contactQueryDTO == null) {
                throw new BusinessException(SystemError.SYS_411);
            }
            dbOrder.setMemberScore(String.valueOf(contactQueryDTO.getMember().getPoint1Value()));
        }
        seriesOrderMapper.updateById(dbOrder);

        return Result.success();
    }

    /**
     * 使用积分计算
     */
    @Override
    public Result usePointsCalculation(SeriesOrderCollectionUsePointsCalculationReq req, TokenUser currentUser) {
        if (req.getPoints() == null) {
            return Result.failed(SystemError.SYS_409);
        }

        SeriesOrder dbOrder = seriesOrderMapper.selectById(req.getOrderId());
        if (StringUtils.isBlank(dbOrder.getMemberMobile())) {
            return Result.failed(SeriesOrderErrorCode.MEMBER_NOT_FOUND_ERROR);
        }

        CrmMemberQueryReq crmMemberQueryReq = new CrmMemberQueryReq(QueryType.PHONE.getCode(), dbOrder.getMemberMobile(), null);
        CrmAccountDTO crmAccountDTO = iCrmMemberService.queryAccountDetail(crmMemberQueryReq);
        if (crmAccountDTO == null) {
            throw new BusinessException(SeriesOrderErrorCode.USE_POINTS_LIMIT);
        }
        ContactQueryDTO contactQueryDTO = null;
        if (Objects.equals(crmAccountDTO.getType(), CrmAccountType.STAR.getCode())) {
            contactQueryDTO = iCrmMemberService.queryMember(crmMemberQueryReq);
            if (contactQueryDTO == null) {
                throw new BusinessException(SeriesOrderErrorCode.USE_POINTS_LIMIT);
            }
        } else {
            throw new BusinessException(SeriesOrderErrorCode.USE_POINTS_LIMIT);
        }

        MainDataCurrencyUpdateStatusReq cnyCurrencyUpdateStatusReq = new MainDataCurrencyUpdateStatusReq();
        cnyCurrencyUpdateStatusReq.setId(CurrencyIdCode.CNY.getCode());
        Result<MainDataCurrencyQueryDTO> cnyCurrencyQueryDTOResult = iMainDataCurrencyService.query(cnyCurrencyUpdateStatusReq);
        if (!cnyCurrencyQueryDTOResult.isSuccess() || cnyCurrencyQueryDTOResult.getData() == null) {
            return Result.failed(SystemError.SYS_411);
        }
        MainDataCurrencyQueryDTO cnyCurrencyQueryDTO = cnyCurrencyQueryDTOResult.getData();

        QueryWrapper<SeriesOrderTouristInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getOrderId, req.getOrderId());
        queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getId, req.getTouristId());
        queryWrapper2.lambda().eq(SeriesOrderTouristInfo::getIsDeleted, IsDeletedCode.NO.getCode());
        SeriesOrderTouristInfo touristInfo = seriesOrderTouristInfoMapper.selectOne(queryWrapper2);
        if (touristInfo == null) {
            return Result.failed(SystemError.SYS_411);
        }

        //可抵扣金額（HKD）=團費+調整費用（不包括簽證、保險、更改旅客資料）
        QueryWrapper<SeriesOrderTouristFeeAdjust> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getTouristId, req.getTouristId());
        queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getAdjustType, AdjustTypeCode.ADJUST.getCode());
        queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getIsDeleted, IsDeletedCode.NO.getCode());
        List<SeriesOrderTouristFeeAdjust> feeAdjustList = seriesOrderTouristFeeAdjustMapper.selectList(queryWrapper);
        BigDecimal touristAmount = touristInfo.getGroupFee();
        for (SeriesOrderTouristFeeAdjust feeAdjust : feeAdjustList) {
            if (Objects.equals(feeAdjust.getPlusType(), PlusTypeCode.PLUS.getCode())) {
                touristAmount = touristAmount.add(feeAdjust.getAmount());
            } else if (Objects.equals(feeAdjust.getPlusType(), PlusTypeCode.SUBTRACT.getCode())) {
                touristAmount = touristAmount.subtract(feeAdjust.getAmount());
            }
        }

        BigDecimal points = BigDecimal.valueOf(req.getPoints());
        MathContext context = new MathContext(2, RoundingMode.HALF_DOWN);

        BigDecimal memberPoints = BigDecimal.valueOf(contactQueryDTO.getMember().getPoint1Value());

        //可用積分=可抵扣金額（HKD）÷人民幣CRM匯率×100
        BigDecimal availablePoints = (touristAmount.divide(cnyCurrencyQueryDTO.getCrmExchangeRate(), context)).multiply(
                new BigDecimal(100));


        //本次抵扣：積分抵扣金額（HKD）= （積分數÷100)×人民幣CRM匯率
        BigDecimal deductionAmount = (points.divide(
                new BigDecimal(100), context)).multiply(
                cnyCurrencyQueryDTO.getCrmExchangeRate());

        SeriesOrderUsePointsCalculationDTO dto = new SeriesOrderUsePointsCalculationDTO();
        dto.setMemberPoints(memberPoints);
        dto.setAvailablePoints(availablePoints);
        dto.setDeductionAmount(deductionAmount);

        return Result.success(dto);
    }

    /**
     * 驳回
     *
     * @param collectionNumber 收款单号
     * @param rejectInfo       驳回信息
     * @param tokenUser
     * @return
     */
    @Transactional
    @Override
    public Result<Long> reject(String collectionNumber, String rejectInfo, TokenUser tokenUser) {
        validateNotBlank(collectionNumber);
        QueryWrapper<SeriesOrderCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("collection_number",collectionNumber);
        queryWrapper.eq("is_deleted",0);
        SeriesOrderCollection entity = seriesOrderCollectionMapper.selectOne(queryWrapper);
        if (entity == null){
            throw new BusinessException(SystemError.SYS_411);
        }
        fillUpdateEntity(entity, tokenUser);
        entity.setStatus(5);
        entity.setRejectMsg(rejectInfo);
        int update = seriesOrderCollectionMapper.updateById(entity);
        if (update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return newResult(entity.getId());
    }

    /**
     * 确认收款(内部接口)
     *
     * @param collectionNumber
     * @param tokenUser
     * @return
     */
    @Transactional
    @Override
    public Result<Long> confirmCollection(String collectionNumber, TokenUser tokenUser) {
        validateNotBlank(collectionNumber);
        QueryWrapper<SeriesOrderCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("collection_number",collectionNumber);
        queryWrapper.eq("is_deleted",0);
        SeriesOrderCollection entity = seriesOrderCollectionMapper.selectOne(queryWrapper);
        if (entity == null){
            throw new BusinessException(SystemError.SYS_411);
        }
        fillUpdateEntity(entity, tokenUser);
        entity.setStatus(3);
        int update = seriesOrderCollectionMapper.updateById(entity);
        if (update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return newResult(entity.getId());
    }

}
